zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular] Difference between ngAfterViewInit and ngAfterContentInit

Angular and between Difference
2023-09-14 08:59:18 时间

Content is what is passed as children. View is the template of the current component.

The view is initialized before the content and ngAfterViewInit() is therefore called before 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>

 

If you run this code, the output for ngAfterViewInit - content should be null.

So if you want to change the child component's props, you cannot do it in 'ngAfterViewInit', you need to do it in 'ngAfterContentInit'.