[Fixed] how to listen of angular template driven form changes

Issue

in my form:

<form>
   <label class="form-check-label">
     <input [(ngModel)]="options.o1" name="o1"
            type="checkbox" class="form-check-input" >
     Option 1
   </label>
   <label class="form-check-label">
     <input [(ngModel)]="options.o2" name="o2"
            type="checkbox" class="form-check-input" >
     Option 2
   </label>
</form>

I want to be informed whenever one of the two checkboxes is changed, not by adding an event handler to each of the checkboxes but by adding an event handler to the form, in reality there are much more fields in the form.

Solution

You can get hold of NgForm directive like:

html

<form #form="ngForm">
   ...
</form>

ts

@ViewChild('form') ngForm: NgForm;

for Angular 9 and above you should use static: true option:

@ViewChild('opportunityForm', { static: true }) ngForm: NgForm;

and then listen valueChanges on NgForm.form

ts

ngOnInit() {
  this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
    console.log(x);
  })
}

ngOnDestroy() {
  this.formChangesSubscription.unsubscribe();
}

ng-run demo

Leave a Reply

(*) Required, Your email will not be published