更新ngAfterContentInit中的内容查询

我是Angular的新手,我从课本中看到了一些代码,如下所示:

...
@ContentChildren(PaCellColor)
 contentChildren: QueryList<PaCellColor>;

ngAfterContentInit() {
   this.contentChildren.changes.subscribe(() => {
      setTimeout(() => this.updateContentChildren(this.modelProperty),0);
 });
}

我不明白为什么我们需要使用setTimeout函数?

fangsufang 回答:更新ngAfterContentInit中的内容查询

此处 setTimeOut 用于避免出错     Expression has changed after it was checked. Previous value: 'ngClass: show'. Current value: 'ngClass: hide'

这称为更改检测。当我们使用@contentChild更改父组件中子组件的属性时,Angular内部调用属性的更改检测策略。

当Angular运行验证阶段时,它检测到该属性有一个待处理的更新并引发错误,因此,这里setTimeOut用于异步运行一些代码,以避免更改检测策略错误。

或者您可以告诉角度有关变更检测this.cdref.detectChanges();

供参考,这是堆栈溢出后的帖子,对您有用。Change Detection Strategy

本文链接:https://www.f2er.com/3168456.html

大家都在问