Unknown Coder
Unknown Coder

Reputation: 1740

Enable / Disable button in Angular Form based on API Response

I am using Angular8 with Reactive form. Initially I'm disabling the Submit button until the entire form is filled with valid data.

<div>
  <form>
     ...........
  </for>
  <button [disabled]="(checkifSaveEnabled() && !formCreateNewPlan.valid)" 
       (click)="createNewPlan()">Save</button>
</div>

In the class (TS) file:

checkifSaveEnabled() {
  if (this.formCreateNewPlan.pristine || !this.formCreateNewPlan.valid) {
    return true;
  }
  return false;
}

createNewPlan(): void {
   this.submitted = true;
   this.myservice.create(this.formCreateNewPlan.value).subscribe(result => {
   if (result.success && result.data.planId > 0) {
      ... 
   }
}

Everything is working fine here. But, I want to disable the Button On Submit (to avoid multiple clicks) and Make it enable back if I get any errors from my Service (API) response. How to achieve this?

Upvotes: 1

Views: 6486

Answers (2)

Jasdeep Singh
Jasdeep Singh

Reputation: 8301

You can use submitted that will be true if API is in progress and will become false if API resolves or reject. Now you can use finalize operator to set submitted to false inside it. It will execute after the success or error block of observable.

createNewPlan(): void {
   this.submitted = true;
   this.myservice.create(this.formCreateNewPlan.value)
.pipe(finalize(() => { this.submitted = false; }))
.subscribe(result => {
   if (result.success && result.data.planId > 0) {
   }

}, (error) => {
  console.log(error)
});

Corresponding change in Template

<button [disabled]="submitted || (checkifSaveEnabled() && !formCreateNewPlan.valid)" 
       (click)="createNewPlan()">Save</button>

Upvotes: 4

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

you just need to add one this.submitted in the disabled attribute of button, see below code

<button [disabled]="submitted || (checkifSaveEnabled() && !formCreateNewPlan.valid)" 
       (click)="createNewPlan()">Save</button>

Upvotes: 1

Related Questions