Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 698
Fernando Avatar asked Dec 14 '22 21:12

Fernando


1 Answers

Use nested form group... Group all other formControl in single formGroup on which you want to update your checkbox value...

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);
        })
    }
like image 90
Tejal Avatar answered Dec 29 '22 07:12

Tejal