Search code examples
angularangular-forms

Detect template driven form change from the component


I have a template-driven form

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

I need to detect if form becomes dirty in component.ts file.

I know I can access form using @ViewChild in the component

@ViewChild('myForm') myForm;

Using this.myForm.statusChanges only gives me form status (VALID, INVALID etc), and it doesn't say if the form became dirty. this.myForm.valueChanges only gives new values that were entered in the form, and doesn't specify if form is pristine or dirty.

Is there an easy way to access dirty state of a template-driven form in the component, when form changes? Thanks.


Solution

  • Well you're already being notified if the status changes, which will be triggered anytime a form input's value is changed. So there's no reason you cannot use that to check to see if the form is dirty, since when the form does become dirty, it will result in statusChanges being fired:

      @ViewChild(NgForm) form: NgForm;
    
      ngOnInit() {
        this.form.statusChanges.subscribe(() => {
          console.log("Is form dirty yet: " + this.form.dirty);
        });
    

    As soon as the form becomes dirty, the subscription will be fired.