how to listen of angular template driven form changes

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.

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

I used accepted answer and base on that I create a demo version for whom concern.

TS file

export class AppComponent {
  
  options: any;
  formChangesSubscription: any;
  @ViewChild('form') ngForm: NgForm;

  updated: any;

  constructor() {
    this.options = { o1: true, o2: false }
  }

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

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

HTML file

<form #form="ngForm">
  <label class="form-label">
     <input [(ngModel)]="options.name" name="name"
            type="text" class="form-input" >
     
   </label>
   <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>

<label>{{updated?.o1}}</label>
<label>{{updated?.o2}}</label>
<label>{{updated?.name}}</label>

https://stackblitz.com/edit/angular-change-template-form?file=src/app/app.component.ts

You should use reactive form as @Remify mentioned and after that you can try this:

this.form.valueChanges.subscribe(() => {
     console.log('form changed');
});

To use reactive form check the angular documentation:

https://angular.io/guide/reactive-forms


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts