【问题标题】:Is there a way to programmatically find the number of default values or skip all default values of a formGroup in Angular?有没有办法以编程方式查找默认值的数量或跳过 Angular 中 formGroup 的所有默认值?
【发布时间】:2021-04-22 15:20:52
【问题描述】:

我有一个具有一些默认值的 formGroup,即非空值。我想对这个 formGroup 的变化做出反应,所以我使用this.FG.valueChanges.subscribe()。问题是,此方法还检测默认值并将其解释为更改。为了规避这种不良行为,我做了以下事情:

this.FG.valueChanges.pipe(
      startWith(1),
      distinctUntilChanged(),
      skip(8) // hardcoded
  ).subscribe(v => console.log(`new value: ${v}`));

问题是您可以看到的“8”是硬编码的。表示表单组FG中默认值的个数。

有没有办法以编程方式查找默认值的数量或跳过所有默认值以便仅订阅反映用户交互的新值?

编辑:

这是一个显示如何添加默认值的片段:

  ngOnInit(): void {
    this.FG = new FormGroup({
      minSaveFG: new FormGroup({
        currentMeasure: new FormControl({value: null, disabled: !this.editable}, Validators.required)
      }),
      currentStartDate: new FormControl({value: this.calendarInfo.startDate ? this.calendarInfo.startDate : this.initialStartDate,
        disabled: !this.editable && !this.correctionMode}, Validators.required),

在初始化之后调用订阅。

【问题讨论】:

  • 如何分配默认值?你有{ control: this.fb.control(defaultValue) } 之类的东西,还是在订阅后分配默认值?
  • 我认为您应该filter 运算符过滤掉具有有效值的流
  • 为什么不订阅 你给了默认值?另一种方法可以跳过(this.FG.controls.length),但我不太确定最后一个想法
  • 我添加了如何分配默认值的信息。我在初始化后订阅了 ngInit

标签: angular observable angular-reactive-forms onchange formgroups


【解决方案1】:

听起来你正在异步获取这些值并稍后分配它们,因为我没有看到它在最初构建表单时触发。不管是什么问题,解决方案是使用emitEvent: false,这不会使valueChanges 着火:

this.myForm = this.fb.group({
  input1: ["hello", { emitEvent: false }]
});

如果您也使用 setValue 或 patchValue 或任何以某种方式操纵表单的方法,也可以应用相同的方法,例如:

this.myForm.get('input1').setValue('hello2', { emitEvent: false})

附言。组件销毁时记得退订valueChanges!

【讨论】:

  • 我编辑了我的原始帖子以显示如何添加默认值。
  • 是的,你试过我的解决方案了吗?我也喜欢使用表单生成器。如果您已将FG 初始化为new FormGroup 并且在OnInit 中您再次调用new FormGroup,则问题也可能是,如果您调用它两次,那肯定会触发值更改。 (这只是一个猜测,因为我不知道你是否已经初始化它)
猜你喜欢
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 2019-08-17
  • 2023-02-14
  • 2015-03-31
  • 1970-01-01
  • 2018-02-01
  • 2015-01-10
相关资源
最近更新 更多