0

我“修复”了这个错误,但我想确保我没有做我不应该做的事情,因为这感觉不对……</p>

这是我的人为示例,我有两个组件faqComponentquestionAnswerComponent

<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?

4

1 回答 1

1

这是 中解决的问题,在 ViewChildren 和 ViewContent 上v8有一个明确的标志。static所以,如果你ng update @angular/core,更新原理图将添加static: false到你的,questionAnswers因为它会检测到它们是动态的,并且它们将在之后可用ngAfterViewInit

另一方面,我不太确定此更改是否改进了更改检测并消除了异常,您可以升级并告诉我们:D 但您的方法似乎是正确的,因为这是我们必须在 v7 中避免此错误的方法,并且希望它不会在 v8 中发生。
快乐的 ng 编码!

于 2019-06-19T01:24:50.343 回答