Here is by Component which has a ViewChild referring to #h1
in the html:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1 #h1 *ngIf="showh1">
Welcome to {{title}}!
</h1>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
public showh1: boolean = false;
@ViewChild('h1') h1: ElementRef;
ngOnInit() {
setTimeout(() => { //http.get in actual scenario
this.showh1 = true;
console.log('h1:' + this.h1); //h1:undefined
setTimeout(() => {
console.log('h2:' + this.h1); //h2:[object Object]
}, 1);
}, 1000);
}
}
Why this.h1
is undefined
at console.log('h1:' + this.h1);
?
Update 2020 Nov
You wouldn't be in this situation if you are using latest Angularv9 which has static option on @ViewChild
.