简体   繁体   中英

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

I have a bad news for you : Use a reactive form. They are exactly what you describe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM