【问题标题】:Change detection seems to not work in a dynamically instantiated component更改检测似乎不适用于动态实例化的组件
【发布时间】:2019-12-16 21:21:32
【问题描述】:

(工作演示here

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

footer.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);
  }

}

footer.component.html

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

当添加到带有app-footer 的模板时,这个组件就像一个魅力。

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

app.component.ts

constructor(private _bottomSheet: MatBottomSheet) {}

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

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

【问题讨论】:

标签: angular typescript angular-material


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2013-12-18
相关资源
最近更新 更多