我有一个表格 first_name
和 last_name
字段。
当这两个字段都输入了值时,我希望在同一表单中启用另一个 formControl。
我知道我可以像这样订阅更改:
createForm() {
this.myForm = new FormGroup({
first_name: this.first_name,
last_name: this.last_name,
email: this.email,
mobile: this.mobile,
salutation: this.salutation
});
this.myForm.valueChanges.subscribe(data => console.log('form changes', (!data.first_name == !data.last_name)));
}
当两个值都设置时,它会记录到控制台并显示“true”。
从this thread可以看出在 Angular github 上,我们不能/不应该将其设置为属性并绑定(bind) [disabled]=<booleanProperty>
(核心团队似乎仍在处理这个问题)。
那么我如何使用上面的 valueChanges 流的结果将另一个控件实际设置为启用状态?
在 OnInit 中,它根据指南被禁用:
this.salutation = new FormControl({value:'', disabled: true}, Validators.required);
更新
抱歉,我忘了说我已经在 OnInit 中尝试过了:
this.myForm.valueChanges.subscribe(data => {
if (!data.first_name == !data.last_name) {
this.salutation.enable();
};
})
这不起作用,它会抛出控制台错误:Maximum call stack size exceeded
最佳答案
超出的堆栈大小是解决此问题的线索。由于流是“连续的”,我的代码一直将控件设置为启用 - 当然,它只需要启用一次。
所以添加一个检查解决了这个问题,现在它起作用了:
this.myForm.valueChanges.subscribe(data => {
if (!data.first_name == !data.last_name && this.myForm.controls['salutation'].disabled) {
this.myForm.controls['salutation'].enable();
};
})
更多信息 here
关于angular - 简单的 Angular2 Reactive Form 控件启用状态更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228320/