Кнопка X не закрывает предупреждение об ошибке начальной загрузки - PullRequest
0 голосов
/ 20 июня 2019

У меня есть div 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 голосов
/ 20 июня 2019

Какое обнаружение изменений вы используете? Такое 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();
    }

}

...