What is ViewChild in Angular2?

It provides a reference to elements or components in your view:

@Component({
  ...
  directives: [SomeComponent],
  template: `
  <div><span #myVar>xxx</span><div>
  <some-comp></some-comp>`
})
class MyComponent {
  @ViewChild('myVar') myVar:ElementRef;
  @ViewChild(SomeComponent) someComponent:SomeComponent;
  
  ngAfterViewInit() {
    console.log(this.myVar.nativeElement.innerHTML);
    console.log(this.someComponent);
  }
}

IMPORTANT: The variables are not initialized before ngAfterViewInit()

Leave a Comment