簡體   English   中英

Angular 2在擴展類中使用屬​​性,因為ngIf不起作用

[英]Angular 2 using property in extended class for ngIf not working

我為模態創建了一個角度2組件,該組件擴展了一個基本模態類,其中包含一個布爾屬性,指示是否打開模態。 然后我需要在模板中的* ngIf中使用此屬性來顯示/隱藏模態。

問題是,當我調用open方法時,我收到以下錯誤:

Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'

我的模態組件:

@Component({
  selector: 'cmg-modal-create',
  template: require('./modal.create.html')
})
export class ModalCreateComponent extends Modal {
  constructor() {
    super();
  }
}

我的組件模板:

<div class='modal-overlay' *ngIf='isModalOpen'></div>
<section id='modal-create' class='modal' *ngIf='isModalOpen'>
  // modal body
</section>

模態類:

export class Modal {
  protected isModalOpen: boolean = false;

  protected open(): void {
    this.isModalOpen = true;
  }

  protected close(): void {
    this.isModalOpen = false;
  }
}

最后在頂級組件中我調用modals open方法

頂級組件:

@Component({
  directives: [ ModalCreateComponent ],
  selector: 'cmg-project-card',
  template: require('./project-card.html')
})
export class ProjectCardComponent {
  @ViewChild('createModal') createModal: any;

  private openModal(): void {
    this.createModal.open();
  }
}

頂級組件模板:

<cmg-modal-create #createModal></cmg-modal-create>

此錯誤消息意味着,假設您沒有在角度本身中遇到錯誤,那么僅僅為了檢索要呈現到視圖的數據而調用的內容正在更改該值。 要正確修復它,您需要找到它是什么並更改它以消除其副作用。

導入以下內容:

import { ChangeDetectorRef } from '@angular/core';

然后加入ChangeDetectorRef到你的構造和使用detectChanges()方法改變布爾值的時候,是這樣的:

this.changeDetectionRef.detectChanges();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM