how to listen of angular template driven form changes
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