Angular2 FormGroup - 如何确定哪个控件触发值更改

时间:2017-08-10 17:08:23

标签: angular angular2-forms angular2-formbuilder

我希望在表单发生更改时取消选中复选框。该复选框是该表单的一部分,因此我只想在值更改来自该复选框之外的任何其他控件时取消选中它。

我正在订阅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,但是希望避免这样做

1 个答案:

答案 0 :(得分:2)

使用嵌套表单组...将所有其他formControl分组到您要更新复选框值的单个formGroup中...

例如:

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);
        })
    }