skip to Main Content

In my Angular 12 application, I have a reactive form with multiple inputs and a SAVE button which submits the form. The SAVE button is disabled by default and I need to enable it only if ANY of the input values are edited.
I understand this can be done by calling (input) event on each of the HTML inputs but is there a more efficient way of doing this. I mean instead of writing a (input) event on each HTML input, maybe use something which would trigger if any of the inputs is changed.

My HTML Form has the following structure:

<form [formGroup]="profileInfoForm" (ngSubmit)="submitProfileInfoForm()">
   <input class="form-control" type="text" formControlName="firstName" name="firstName
</form> 

2

Answers


  1. You can do this using valueChanges in your form and a boolean variable to hold the original unchanged status:

    isFormEdited: boolean = false;
    
    ngOnInit() {
    
      this.profileInfoForm.valueChanges
        .pipe(takeUntil(this._unsubscribeAll))
        .subscribe(() => {
          this.isFormEdited = true;
        });
    
    }
    

    So when isFormEdited turns to true, you enable the button

    <button [disabled]="!isFormEdited">Save</button>
    
    Login or Signup to reply.
  2. You can make use of pristine.
    Control is pristine if the user has not changed its value.

    sample code

    <button [disabled]="xyzForm.pristine"class="xyz">Save</button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search