angular - 更改检测似乎不适用于动态实例化的组件
问题描述
(工作演示在这里)
我制作了一个非常简单的组件,它显示 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
吗?
解决方案
Material BottomSheet 使用“mat-bottom-sheet-container”包装您的组件,它将 ChangeDetection 设置为 OnPush,以便您的 FooterComponent 继承它。您必须通过注入 ChangeDetectorRef 并调用“markForCheck”方法来手动触发更改检测;)
推荐阅读
- sql - 在属性超集中显示实例拥有哪些属性的查询
- javascript - 如何使用反应挂钩获取网络摄像头提要?
- php - 将 3 个数组与默认键组合
- c++ - 我的代码中有什么错误。我尝试在课堂上使用数组但出现逻辑错误
- c++ - 尝试使用 VS2015 和 addrinfoW 返回唯一指针时堆栈溢出
- javascript - 第一次调用更改状态的函数不会更新任何字段
- git - 当“git push”到 git Gogs 存储库时,如何从服务器调用脚本?
- sql-server - 如何仅对总和大于 SQL 查询的那些进行平均
- java - 从 bean 抛出的异常:java.lang.NoClassDefFoundError: com/auth0/jwt/algorithms/Algorithm
- android - 无法解析地图符号