Detect if data in an Angular form (not reactive) was changed

According to your comment 'But what if i erase 1 symbol in input and then wright it again (the value is the same, but form was changed)?' I suggest this solution.

The general idea is to store the initial value of the form as separate object (just cloning it). And then create a boolean function which simply iterate through the key-values and compare Updated data with the Initial data. After this just bind the result of this function to your submit button [disabled]="yourCheckMethod(form.value)".


You can try it with the pristine property like this:

<button type="submit" [disabled]="form.pristine">Save</button>

This property checks if your form has changed since it was loaded.


You can check the dirty flag, which tells you if the form is dirty or not.

<button type="submit" [disabled]="!form.dirty">Save</button>

The form becomes dirty if you change some value in it.

Check here for more details: https://angular.io/guide/forms

enter image description here


I had a situation where I did not have a form, adapting it to the question asked here, although mine handles on click and not disabling the button. Angular 7 with TypeScript:

    <!-- user.component.html -->
    .....
    .....
    <div>
      <input [(ngModel)]="user.name">
      <input [(ngModel)]="user.color">
      <button (click)="save()">Save</button>
    </div>
  
    // user.component.ts
    .....
    .....
    lastObjectHash: string;
    User: user = { name: "joe", color: "blue"};  // with name and color on type User 
    
    // Not really a hash, but let's call it that
    getObjectHash(): Promise<string> {
      return util.encodeBase64(JSON.stringify(this.user));
    }

    ngAfterViewInit(): void {
      this.getObjectHash().then(value => this.lastObjectHash = value);
    }

    save() {
      this.getObjectHash().then(value => { 
        if (this.lastObjectHash === value) {
          alert("You did not change name or color");
          return;
        }
        // Save user changes....
        this.userService.save(this.user);  // Or whatever...
      }); 
    }

    // util.ts
    // Just a utility function to BASE64 encode
    .....
    .....
    export const encodeBase64 = async (textString) => {
      return btoa(textString);
    };