javascriptangularionic4

Ionic -angular failed to update view after click on a button


Why after click in a button in the ion-alert component, the view don't get update ? For example if i have a property in my component called sending and a handler for a button of my ion-alert :

  // in my component
  public sending = false;

 constructor(
    public alertCtrl: AlertController,
    ) { }

  async deleteFile() {
    const alert =  await this.alertCtrl.create({
      header: 'Deseas eliminar el archivo?',
      message: '',
      buttons: [
        {
          text: 'Eliminar',
          role: 'eliminar',
          cssClass: 'btn-alert',
          handler: () => {
            this.sending = true;
          }
        }
      ]
    });

     await alert.present();
  }

  <!-- in my view -->
<div> {{  sending  }}  </div>

The view don't update unless i call the angular method ** markForCheck () ** inside the handler.

I am using ionic 4 and angular.

English isn’t my first language, so please excuse any mistakes


Solution

  • Here see my comments inside the code. I hope this explains that this is expected behavior and there are two ways to update the value of "sending" property (inside the handler or onDidDismiss hook):

    import { Component } from '@angular/core';
    import { AlertController } from '@ionic/angular'
    
    @Component({
      selector: 'app-home',
      templateUrl: 'home.page.html',
      styleUrls: ['home.page.css'],
    })
    export class HomePage {
    
      public sending = false;
    
     constructor(
        public alertCtrl: AlertController,
        ) { }
    
      async deleteFile() {
        const alert =  await this.alertCtrl.create({
          header: 'Deseas eliminar el archivo?',
          message: '',
          buttons: [
            {
              text: 'Eliminar',
              role: 'eliminar',
              cssClass: 'btn-alert',
              handler: () => {
                // this update of property "sending" happens in the "alert" component and the HomePage component does not learn about this change until next change detection cycle:
                this.sending = true;
              }
            }
          ]
        });
        await alert.present();
        alert.onDidDismiss().then(() => {
          // this update will happen after "alert" dismiss and within the scope of the HomePage component. 
          this.sending = true;
        });
      }
    }
    

    To play around: https://stackblitz.com/edit/ionic-4-template-psfsbd