Paul Serre
Paul Serre

Reputation: 800

Angular template form : disable submit if form didn't change

Here's my code

          <form (ngSubmit)="onSubmit()" #f="ngForm">
            <input placeholder="Order ID" type="text" id="orderId" class="form-control" 
            name="orderId" [(ngModel)]="orderId" required>
            <button class="btn btn-primary" type="submit" [disabled]="!(f.valid && f.dirty)">Search</button>
          </form>

I was expecting for the button to be disabled if input did not change but it did not. Does anyone know why?

Upvotes: 0

Views: 1722

Answers (2)

Eliseo
Eliseo

Reputation: 58099

As Robert say you can "play" with pristine. e.g.

<form [formGroup]="form">
  <input formControlName="control">
  <button (click)="submit(form)" 
          [disabled]="!form.valid || form.pristine">submit</button>
</form>

  submit(form)
  {
    if (form.valid) //if valid mark as "pristine"
    {
      form.markAsPristine();
      console.log("submited") //do something
    }
    else
      form.markAllAsTouched(); //mark all the controls as touched
                               //to show the errors
  }

stackblitz

Upvotes: 0

robert
robert

Reputation: 6152

dirty / ! pristine means the user has made a modification

In your case if you enter something and then revert it to it's original value Form will still remain dirty

To check if there are any difference you need to implement your own method.

Demo

Upvotes: 2

Related Questions