Search code examples
angularloaderangular-servicesangular-formsangular-observable

Remove Loader in When Click Cancel in Angular 4


I have this npm package called ngx-loading. I have to set this.loading = true and this.loading = false to make it show and not to show. The problem comes when i use the alert in javascript. The alert shows "ok"and "cancel". When i click "ok" the loader disappears while if i click "cancel" and "x" it still appears? How can i make the loader disappears when i click the cancel or x button? Here's what i've done below.

TS

onUpdate(form: NgForm) {
  this.loading = true;

  name =  form.value.name,

  if (confirm('Are you sure you want to update?')) {
    this.subscription = this.prodService.update(name)
    .subscribe(
      data => {
       this.loading = false;
       console.log(data); 
     },
     error => {
       this.loading = false;
       console.log(error);
     });
  }
}

Solution

  • Simply add an else condition when the user clicks cancel.

    onUpdate(form: NgForm) {
      this.loading = true;
    
      name =  form.value.name,
    
      if (confirm('Are you sure you want to update?')) {
        this.subscription = this.prodService.update(name)
        .subscribe(
          data => {
           this.loading = false;
           console.log(data); 
         },
         error => {
           this.loading = false;
           console.log(error);
         });
      } else {
        this.loading = false;
      }
    }