Issue
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?
Solution
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>
Answered By - Jasdeep Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.