I want to access the DOM of a component using ViewChild
. But when I try to access the nativeElement
property, it's undefined
.
Below is the snippet.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { AlertComponent } from './alert.component';
@Component({
selector: 'app-root',
template: `
<app-alert #alert>My alert</app-alert>
<button (click)="showAlert()">Show Alert</button>`
})
export class AppComponent implements AfterViewInit {
@ViewChild('alert') alert;
showAlert() {
console.log('alert (showalert)', this.alert.nativeElement);
this.alert.show();
}
ngAfterViewInit() {
console.log('alert (afterviewinit)', this.alert.nativeElement);
}
}
Please take a look at the plunk.