[英]Angular2 FormGroup - How to determine which control triggered valuechanges
I want to uncheck a checkbox any time there is a change in the form. 我希望在表单发生更改时取消选中一个复选框。 The checkbox is part of that form so I want to only uncheck it when value change comes from any other control aside from that checkbox. 该复选框是该表单的一部分,因此我只想在值更改来自该复选框之外的任何其他控件时取消选中它。
I am subscribing to a FormGroup's value changes like so 我正在订阅FormGroup的值更改
import { FormBuilder, FormGroup } from '@angular/forms';
export class App {
form : FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
firstName: 'Thomas',
lastName: 'Mann',
... many more fields ...
checkbox: true
})
this.form.valueChanges.subscribe(data => {
//if valueChange was not triggered by change in the checkbox
this.form.get('checkbox').setValue(false);
})
}
}
I could subscribe to valueChanges in every other control individually, but would like to avoid doing so 我可以单独订阅每个其他控件中的valueChanges,但是我们希望避免这样做
Use nested form group... Group all other formControl in single formGroup on which you want to update your checkbox value... 使用嵌套表单组...将所有其他formControl分组到您要更新复选框值的单个formGroup中...
For example : 例如 :
import { FormBuilder, FormGroup } from '@angular/forms';
export class App {
form : FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
'otherFormField': this.fb.group({
firstName: 'Thomas',
lastName: 'Mann',
... many more fields ...
}),
checkbox: true
})
this.form.otherFormField.valueChanges.subscribe(data => {
//if valueChange was not triggered by change in the checkbox
this.form.get('checkbox').setValue(false);
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.