【问题标题】:Ionic -angular failed to update view after click on a button单击按钮后,Ionic -angular 无法更新视图
【发布时间】:2019-12-10 13:42:36
【问题描述】:

为什么点击 ion-alert 组件中的按钮后,视图没有更新? 例如,如果我的组件中有一个名为 sending 的属性和我的 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>

除非我在处理程序中调用角度方法 ** markForCheck () **,否则视图不会更新。

我正在使用 ionic 4 和 angular。

英语不是我的母语,如有错误请见谅

【问题讨论】:

  • 我猜alertCtrlalert 是否不在 Angular 区域中运行,因此需要手动检测更改。发布您的模板,并请解释警报是什么

标签: javascript angular ionic4


【解决方案1】:

在这里查看我的 cmets 代码。我希望这可以解释这是预期的行为,并且有两种方法可以更新“发送”属性的值(在处理程序或 onDidDismiss 挂钩内):

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

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多