javascript - 单击按钮后 Ionic-Angular 无法更新 View

标签 javascript angular ionic4

为什么单击 ion-alert 组件中的按钮后, View 没有更新? 例如,如果我的组件中有一个名为 sending 的属性以及 ionic 警报按钮的处理程序:

  // 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>

除非我在处理程序内调用 Angular 方法 ** markForCheck () **,否则 View 不会更新。

我正在使用 ionic 4 和 Angular。

英语不是我的母语,所以请原谅任何错误

最佳答案

这里查看我在代码中的注释。我希望这解释了这是预期的行为,并且有两种方法可以更新“发送”属性的值(在处理程序或 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;
    });
  }
}

玩一下: https://stackblitz.com/edit/ionic-4-template-psfsbd

关于javascript - 单击按钮后 Ionic-Angular 无法更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59256335/

相关文章:

angular - 在 Angular 中使用多个共享模块

ionic4 - 电容相机 API 在网络上运行时抛出错误

javascript - 仅使用 javascript 提示用户至少选择一个复选框

javascript - JavaScript 函数速度太快

data-binding - 使用 ngModel 的 Angular 2 双向绑定(bind)不起作用

angular - 如何为 Resolve 编写测试

javascript - 在 Angular 中的 Controller 之间绑定(bind)数据

javascript - 匹配javascript中uri段的正则表达式

javascript - Ionic 4 与 Vue js - ion-menu 内的 ion-content 不处理任何点击

ionic4 - 单击 ionic 幻灯片转到某些幻灯片