函数 ngAfterContentInit 和 ngAfterViewInit 有什么区别?
最佳答案
内容是作为子级传递的,通常会投影到组件的某些<ng-content>
元素上。
View 是当前组件的模板。
在内容之后初始化 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);
}
}
<parent-cmp><div #myContent>foo</div></parent-cmp>
如果运行此代码,则
ngAfterViewInit - content
的输出应为null
。有关生命周期挂钩的更多详细信息,请参见https://angular.io/guide/lifecycle-hooks。
关于angular - ngAfterContentInit和ngAfterViewInit有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37962821/