Angular2 FormGroup - 如何确定哪个控件触发了值更改
Angular2 FormGroup - How to determine which control triggered valuechanges
我想在表单发生变化时取消选中复选框。该复选框是该表单的一部分,因此我只想在值更改来自该复选框以外的任何其他控件时取消选中它。
我正在订阅 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);
})
}
}
我可以单独订阅每个其他控件中的 valueChanges,但我想避免这样做
使用嵌套表单组...将所有其他表单控件分组到您要更新复选框值的单个表单组中...
例如:
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);
})
}
我想在表单发生变化时取消选中复选框。该复选框是该表单的一部分,因此我只想在值更改来自该复选框以外的任何其他控件时取消选中它。
我正在订阅 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);
})
}
}
我可以单独订阅每个其他控件中的 valueChanges,但我想避免这样做
使用嵌套表单组...将所有其他表单控件分组到您要更新复选框值的单个表单组中...
例如:
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);
})
}