有没有一种方法可以通过编程找到默认值的数量,或者跳过Angular中formGroup的所有默认值



我有一个formGroup,它有一些默认值,即非null。我想对此表单Group中的更改做出反应,所以我使用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),

在初始化之后调用subscribe。

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

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

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

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

PS。组件损坏时记得取消订阅valueChanges

相关内容

最新更新