【发布时间】: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