ngAfterContentChecked() 无法理解 + 角度 2

Posted

技术标签:

【中文标题】ngAfterContentChecked() 无法理解 + 角度 2【英文标题】:ngAfterContentChecked() not understandable + angular 2 【发布时间】:2017-11-23 19:53:16 【问题描述】:

一段时间以来,我一直试图弄清楚ngAfterContentChecked()ngAfterViewChecked() 的含义。尝试了各种帖子,但仍然无法理解它们的确切含义。以下是 angular.io 中给出的定义。 有人可以用一些很好的例子来解释它吗?

ngAfterViewChecked()- Respond after Angular checks the component's views and child views.
Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().
A component-only hook.

ngAfterContentChecked()- Respond after Angular checks the content projected into the component.
Called after the ngAfterContentInit() and every subsequent ngDoCheck().
A component-only hook.

【问题讨论】:

尝试阅读:angular.io/guide/lifecycle-hooks#aftercontent 和 angular.io/guide/lifecycle-hooks#afterview 【参考方案1】:

假设我们有这个 html

<div> // div A
  <app-my-component>
    <div>
      this is some content for the component app-my-component
    </div>
  </app-my-component>
</div> // div B

假设我们有这个组件

@Component(
  selector: 'app-my-component',
  template: `
    <div> // div C
      here is the View HTML but below we receive content html
      <ng-content></ng-content>
    </div> // div D
  `
)

在我们的组件中,从 div A 一直到 div B,即视图。因此,当我们到达 B 时,AfterViewChecked 将运行。内容是驻留在 ng-content 标记中的所有内容。因此,当我们到达 div D 时,AfterContentChecked 将运行。但是,我的意思是对视图的任何更改都可能触发额外的 AfterViewCheck,这也应该触发 AfterContentCheck

【讨论】:

以上是关于ngAfterContentChecked() 无法理解 + 角度 2的主要内容,如果未能解决你的问题,请参考以下文章