设置新值时不会触发 FormControl 的 valueChanges
FormControl's valueChanges doesn't trigger when new value set
在下面的示例中没有触发 valueChanges 非常奇怪。这是一个错误吗?
我必须取消订阅 valueChanges 吗?
subscription = Subscription.EMPTY;
constructor() {
this.form = new FormGroup({
id: new FormControl(0, { validators: [] })
});
}
ngOnInit(): void {
let sub = this.id.valueChanges.subscribe((value: number) => this.tokenSelected(value));
//Value changes doesn't trigger because of this line
//but it works if I remove it.
this.subscription.add(sub);
}
get id() { return this.form.get('id')!; }
setId() {
this.id.setValue(1);
}
It is very weird that valueChanges doesn't trigger in below example. Is this a bug ?
这不是错误,valueChanges
不会触发,因为它已在 ngOnInit
内退订。
问题在于以下作业:
subscription = Subscription.EMPTY;
它创建一个新订阅并将其 closed
属性 设置为 true
。 closed
标志用于表示订阅是否已经取消订阅。
当您使用 add(sub)
添加新订阅时,它会在内部检查订阅是否已关闭,并且由于 closed
属性 设置为 true
,新添加的订阅 sub
自动退订。因此 valueChanges
在你的情况下没有触发。
相反,您可以进行如下初始化:
subscription = new Subscription();
在下面的示例中没有触发 valueChanges 非常奇怪。这是一个错误吗? 我必须取消订阅 valueChanges 吗?
subscription = Subscription.EMPTY;
constructor() {
this.form = new FormGroup({
id: new FormControl(0, { validators: [] })
});
}
ngOnInit(): void {
let sub = this.id.valueChanges.subscribe((value: number) => this.tokenSelected(value));
//Value changes doesn't trigger because of this line
//but it works if I remove it.
this.subscription.add(sub);
}
get id() { return this.form.get('id')!; }
setId() {
this.id.setValue(1);
}
It is very weird that valueChanges doesn't trigger in below example. Is this a bug ?
这不是错误,valueChanges
不会触发,因为它已在 ngOnInit
内退订。
问题在于以下作业:
subscription = Subscription.EMPTY;
它创建一个新订阅并将其 closed
属性 设置为 true
。 closed
标志用于表示订阅是否已经取消订阅。
当您使用 add(sub)
添加新订阅时,它会在内部检查订阅是否已关闭,并且由于 closed
属性 设置为 true
,新添加的订阅 sub
自动退订。因此 valueChanges
在你的情况下没有触发。
相反,您可以进行如下初始化:
subscription = new Subscription();