Dar*_*iak 22 angular2-template angular
函数ngAfterContentInit和 ngAfterViewInit有什么区别?
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
Deb*_*nda 11
下图显示了挂钩的顺序.来源:Angular Lifecycle Hooks
ngAfterContentInit:在初始化组件外部内容之后调用此方法.
ngAfterViewInit:在组件视图及其子视图初始化之后调用此方法.