ngAfterContentInit和ngAfterViewInit有什么区别?

Dar*_*iak 22 angular2-template angular

函数ngAfterContentInitngAfterViewInit有什么区别

Gün*_*uer 24

内容是通常作为子项传递<ng-content>给组件的某个元素的内容.
View是当前组件的模板.

视图在内容之后初始化,ngAfterViewInit()因此被调用ngAfterContentInit().

@Component({
  selector: 'parent-cmp',
  template: '<div #wrapper><ng-content></ng-content></div>'
})
class ParentComponent {
  @ViewChild('wrapper') wrapper:ElementRef;
  @ContentChild('myContent') content:ElementRef;

  ngAfterViewInit() {
    console.log('ngAfterViewInit - wrapper', this.wrapper);
    console.log('ngAfterViewInit - content', this.content);
  }

  ngAfterContentInit() {
    console.log('ngAfterContentInit - wrapper', this.wrapper);
    console.log('ngAfterContentInit - content', this.content);
  }
}
Run Code Online (Sandbox Code Playgroud)
<parent-cmp><div #myContent>foo</div></parent-cmp>
Run Code Online (Sandbox Code Playgroud)

如果您运行此代码,输出ngAfterViewInit - content应该是null.

有关生命周期钩子的更多详细信息,请参阅https://angular.io/guide/lifecycle-hooks

  • "因此在ngAfterContentInit()之前调用内容和ngAfterViewInit()之前初始化视图." 似乎不对:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview (5认同)
  • 也许有些事情发生了变化,但这个答案不再正确。`AfterContentInit` 生命周期发生在 `AfterViewInit` 之前。`ngAfterContentInit -wrapper` 的输出未定义。定义了其他输出。请参阅使用 v8 的类似 plunker https://plnkr.co/edit/vZzZyrYnsB46S64B?open=lib%2Fapp.ts&amp;deferRun=1 (4认同)

Deb*_*nda 11

下图显示了挂钩的顺序.来源:Angular Lifecycle Hooks

Angular 2生命周期钩子

ngAfterContentInit:在初始化组件外部内容之后调用此方法.

ngAfterViewInit:在组件视图及其子视图初始化之后调用此方法.

  • “外部内容”到底是什么意思? (4认同)
  • @Nexeuz 外部内容通过 ng-content 指令传递 (2认同)