[英]ExpressionChangedAfterItHasBeenCheckedError with ViewChildren
I “fixed” this error but I wanted to make sure i'm not doing something that i shouldn't be, as this just feels wrong… 我“修复”了这个错误,但是我想确保自己没有做我不应该做的事情,因为这感觉不对…
Here is my contrived example, I have two components faqComponent
and questionAnswerComponent
这是我人为的示例,我有两个组件
faqComponent
和questionAnswerComponent
<app-faq>
<ul>
<li *ngFor="let questionsAnswer of questionsAnswers">
{{ questionsAnswer.question }}
</li>
</ul>
<app-question-answer
question="1. Why Foo Bar when Baz?"
slug="why-foo-bar-when-baz"
[activeSlug]="currentSlug"
>
<p>
Lorem ipsum dolor sit amet
</p>
</app-question-answer>
... // a lot more question answer components
</app-faq>
I want the list to be dynamically generated by the questionsAnswer components on the parent component, This is working the way I want by using view children 我希望列表由父组件上的questionsAnswer组件动态生成,这可以通过使用视图子项来实现我想要的方式
@ViewChildren(QuestionAnswerComponent) questionsAnswers: QueryList<QuestionAnswerComponent>;
with the exception that I get a ExpressionChangedAfterItHasBeenCheckedError
in the log (but it still renders the list for me) 除了我在日志中得到
ExpressionChangedAfterItHasBeenCheckedError
(但它仍为我呈现该列表)
To fix this I found that if i set the faq component change detection strategy to OnPush and then in ngAfterContentChecked trigger a markForCheck()
it gets rid of that error. 为了解决这个问题,我发现如果我将常见问题组件更改检测策略设置为OnPush,然后在ngAfterContentChecked中触发
markForCheck()
它将消除该错误。
So my questions is why is this bad? 所以我的问题是为什么这不好? or is there another way I should be iterating over the viewChildren?
还是我应该遍历viewChildren的另一种方法?
This is the issue addressed in v8
, having a explicit static
flag on ViewChildren and ViewContent. 这是
v8
解决的问题,在ViewChildren和ViewContent上具有显式的static
标志。 So, if you ng update @angular/core
, the update schematic will add the static: false
to your questionAnswers
because it will detect that they are dynamic, and they will be available after ngAfterViewInit
. 因此,如果您对
ng update @angular/core
进行更新,则更新示意图将在您的questionAnswers
ngAfterViewInit
添加static: false
,因为它将检测到它们是动态的,并且在ngAfterViewInit
之后将可用。
In the other hand, I'm not quite sure if this change improves the change detection and removes the exception, you may upgrade and tell us :D but you approach seems right because that's the way we had to avoid this error in v7, and hopefully it won't happen in v8. 另一方面,我不太确定此更改是否可以改善更改检测并消除异常,您可以升级并告诉我们:D但您的方法似乎正确,因为这是我们必须避免在v7中出现此错误的方式,并且希望它不会在v8中发生。
Happy ng-coding! 快乐的ng编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.