首页 > 解决方案 > 更改检测似乎不适用于动态实例化的组件

问题描述

(工作演示在这里

我制作了一个非常简单的组件,它显示 3 秒的消息,然后显示“完成”消息:

页脚.component.ts

import { Component, OnInit } from '@angular/core'

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.scss']
})
export class FooterComponent implements OnInit {

  waiting = true;

  ngOnInit() {
    setTimeout(() => this.waiting = false, 3000);
  }

}

页脚.component.html

<div class="footer">
  <div *ngIf="waiting">Waiting 3s</div>
  <div *ngIf="!waiting">Done !</div>
</div>

这个组件在添加到带有app-footer.

但是,当使用 Material 动态实例化时BottomSheet,不会发生更改检测。该变量waiting具有正确的值,但显示的文本是错误的。我必须手动调用ChangeDetectorRef.

app.component.ts

constructor(private _bottomSheet: MatBottomSheet) {}

showBottomSheet() {
  this._bottomSheet.open(FooterComponent);
}

在查看 StackOverflow 之后,我了解到变化检测与动态实例化组件的行为不同,但似乎唯一的变化是@Input()变量。这是预期的行为吗?它是材料的错误BottomSheet吗?

标签: angulartypescriptangular-material

解决方案


Material BottomSheet 使用“mat-bottom-sheet-container”包装您的组件,它将 ChangeDetection 设置为 OnPush,以便您的 FooterComponent 继承它。您必须通过注入 ChangeDetectorRef 并调用“markForCheck”方法来手动触发更改检测;)


推荐阅读