2

This Angular app consists of only app-root component with a single <div> and a <button>.

When a button is clicked the onClick() function logs to console the div_a object with:

console.log("...onClick() div_a:", this.div_a);

with div_a defined with following statement:

@ViewChild('div_a', { static: false }) div_a: Component;

Question: why both the ngOnInit and constructor functions logs that the div_a is undefined? How to fix the problem of these functions of not being able to use div_a object?

Below is the link to Stackblitz project (please note that the GitHub branch that is linked to this stackblitz project needs to be switched from master to qViewChild branch).

https://stackblitz.com/edit/angular-r9hwbs?file=src%2Fapp%2Fwidget-a%2Fwidget-a.component.html

enter image description here

alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • Rather than `ngOnInit` or the `constructor` you need to look at the `ngAfterViewInit` lifecycle hook, when ViewChild element will have been evaluated. Also - I think that stackblitz link you posted is not right, doesn't seem to match your example code in the question (might be the wrong link?) – Garth Mason Feb 05 '20 at 00:42
  • Thanks for your comment! The GitHub branch that is linked to the `stackblitz` project needs to be switched to `qViewChild` – alphanumeric Feb 05 '20 at 01:24

2 Answers2

6

Based on the docs, ViewChild and ViewChildren queries are run before AfterViewInit, so you'll need to access them there. Just accessing div_a won't work unless you tag it in the template.

Among others, the children you can access are:

  • Any class with the @Component or @Directive decorator
  • A template reference variable as a string (e.g. query <my-component #cmp></my-component> with @ViewChild('cmp'))

So you'll need something like this:

<p #myPara>
  Start editing to see some magic happen :)
</p>
import { Component, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit  {
  @ViewChild('myPara', {static: false}) paragraph;


  ngAfterViewInit() {
    console.log(this.paragraph) // results in -> ElementRef {nativeElement: p}
  }
}

Blitz

Phix
  • 9,364
  • 4
  • 35
  • 62
  • Why not to use `ngAfterContentInit` instead? What is the difference between `ngAfterViewInit` and `ngAfterContentInit`? – alphanumeric Feb 05 '20 at 01:12
  • https://stackoverflow.com/questions/37962821/what-is-the-difference-between-ngaftercontentinit-and-ngafterviewinit – Phix Feb 05 '20 at 01:28
0

When using @ViewChild DO NOT use ngOnInit or constructor because it is not yet loaded. Use the ngAfterViewInit()

Dharman
  • 30,962
  • 25
  • 85
  • 135