本文介绍了ngAfterContentInit和ngAfterViewInit有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数 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有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 09:35