Angular2的ngOnInit和ngAfterViewInit有什么区别?

Zhi*_*Sun 48 ngoninit angular

我无法理解ngOnInit和之间的区别ngAfterViewInit.

我发现它们之间唯一的区别是@ViewChild.根据以下代码,elementRef.nativeElement其中的内容是相同的.

我们应该使用什么场景ngAfterViewInit

@Component({
  selector: 'my-child-view',
  template: `
  <div id="my-child-view-id">{{hero}}</div>
  `
})
export class ChildViewComponent {
  @Input() hero: string = 'Jack';
}

//////////////////////
@Component({
  selector: 'after-view',
  template: `
    <div id="after-view-id">-- child view begins --</div>
      <my-child-view [hero]="heroName"></my-child-view>
    <div>-- child view ends --</div>`
   + `
    <p *ngIf="comment" class="comment">
      {{comment}}
    </p>
  `
})
export class AfterViewComponent implements AfterViewInit, OnInit {
  private prevHero = '';
  public heroName = 'Tom';
  public comment = '';

  // Query for a VIEW child of type `ChildViewComponent`
  @ViewChild(ChildViewComponent) viewChild: ChildViewComponent;

  constructor(private logger: LoggerService, private elementRef: ElementRef) {
  }

  ngOnInit(){
    console.log('OnInit');
    console.log(this.elementRef.nativeElement.querySelector('#my-child-view-id'));
    console.log(this.elementRef.nativeElement.querySelector('#after-view-id'));
    console.log(this.viewChild);
    console.log(this.elementRef.nativeElement.querySelector('p'));
  }

  ngAfterViewInit() {
    console.log('AfterViewInit');
    console.log(this.elementRef.nativeElement.querySelector('#my-child-view-id'));
    console.log(this.elementRef.nativeElement.querySelector('#after-view-id'));
    console.log(this.viewChild);
    console.log(this.elementRef.nativeElement.querySelector('p'));
  }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 58

ngOnInit()之后被称为ngOnChanges()被称为第一次.ngOnChanges()每次通过变化检测更新输入时调用.

ngAfterViewInit()在最初呈现视图后调用.这就是为什么@ViewChild()取决于它.在呈现视图成员之前,您无法访问它们.

  • "_你在渲染之前无法访问视图成员_" - 那么你如何解释`onNgInit`上的`ViewChild`(vc)是否可用?https://plnkr.co/edit/AzhRe6bjnuPLKJWEJGwp?p=preview,你能解释一下吗? (3认同)
  • 当您说_rendered_时,您的意思是它出现在屏幕上吗?(或发送以渲染以显示在屏幕上) (2认同)
  • 当它被添加到DOM时.如果设置`display:hidden`,则直到渲染,但在屏幕上不可见.但是如果你使用浏览器devtools调查DOM,你将能够看到标记. (2认同)
  • @Royi我无法在手机上打开您的Plunker,它将花费几天时间,直到我返回计算机。静态添加的元素已经在ngOnInit中可用。如果您有* ngFor`呈现的内容(从数据传递到@Input),则该内容在ngOnInit中尚不可用。 (2认同)
  • 非常感谢您的回复.这正是情景.所以我想这就是它.https://i.imgur.com/Vbajl4F.jpg.享受你的假期. (2认同)

Vis*_*ati 18

ngOnInit()在第一次检查指令的数据绑定属性之后,以及在检查其任何子项之前调用.实例化指令时仅调用一次.

ngAfterViewInit()在组件的视图之后调用,并创建其子视图.它是一个生命周期钩子,在组件的视图完全初始化后调用.

  • “在组件的视图完全初始化之后”表明是在 ngOnInit 之后,但事实并非如此(ngAfterViewInit 可以在 ngOnInit 之前/期间调用) (2认同)