问题描述
函数 ngAfterContentInit()
和 ngAfterViewInit()
有什么区别?
推荐答案
内容是作为子级传递的内容,通常投影到组件的某些< ng-content>
元素上.
视图是当前组件的模板.
Content is what is passed as children usually to be projected at some <ng-content>
element of a component.
View is the template of the current component.
在内容之后初始化视图,因此在 ngAfterContentInit()
之后调用 ngAfterViewInit()
.
The view is initialized after the content and ngAfterViewInit()
is therefore called after 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
.
If you run this code, the output for ngAfterViewInit - content
should be null
.
有关生命周期挂钩的更多详细信息,请参见 https://angular.io/guide/lifecycle-hooks
More details about lifecycle hooks see https://angular.io/guide/lifecycle-hooks
这篇关于ngAfterContentInit()和ngAfterViewInit()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!