X按钮未关闭引导错误警报

时间:2019-06-20 16:22:00

标签: html angular typescript alert

我有一个显示错误的错误div:

<div *ngIf="isScreenError" class="alert alert-danger alert-dismissible">
  <button class="close" type="button" data-dismiss="alert" (click)='closeAlert()'>×</button>
  ERROR: {{errorMessage.error.message}}</div>

关闭警报功能只是将'isScreenError'设置为false。

 closeAlert(){
    this.isScreenError=false;
  }

为什么我的div不关闭?不知道我在做什么错。

谢谢!

1 个答案:

答案 0 :(得分:-1)

您使用哪种类型的变化检测?是OnPush吗?

https://angular.io/api/core/ChangeDetectionStrategy

enum ChangeDetectionStrategy {
  OnPush: 0
  Default: 1
}

OnPush: 0   
Use the CheckOnce strategy, meaning that automatic change detection is deactivated until reactivated by setting the strategy to Default (CheckAlways). Change detection can still be explicitly invoked. This strategy applies to all child directives and cannot be overridden.

如果您使用OnPush,则应手动启动更改检测。

https://angular.io/api/core/ChangeDetectorRef detectChanges()或markForCheck()

示例:

import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'alert',
  template: `
    <div *ngIf="isScreenError" class="alert alert-danger alert-dismissible">
        <button class="close" type="button" data-dismiss="alert" (click)='closeAlert()'>×</button>
        ERROR: {{errorMessage.error.message}}
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AlertComponent {
    public errorMessage = {
        error: {
            message: 'Some message'
        }
    };

    public isScreenError = true;

    constructor(
        private cd: ChangeDetectorRef,
    ) { }


    public closeAlert(): void {
        this.isScreenError = false;
        this.cd.markForCheck();
    }

}