我“修复”了这个错误,但我想确保我没有做我不应该做的事情,因为这感觉不对……</p>
这是我的人为示例,我有两个组件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>
我希望该列表由父组件上的 questionsAnswer 组件动态生成,这是通过使用视图子组件以我想要的方式工作的
@ViewChildren(QuestionAnswerComponent) questionsAnswers: QueryList<QuestionAnswerComponent>;
除了我ExpressionChangedAfterItHasBeenCheckedError
在日志中得到一个例外(但它仍然为我呈现列表)
为了解决这个问题,我发现如果我将 faq 组件更改检测策略设置为 OnPush,然后在 ngAfterContentChecked 触发器中markForCheck()
消除该错误。
所以我的问题是为什么这很糟糕?还是有另一种方法我应该迭代viewChildren?