我想使用ViewChild
访问组件的DOM.但当我try 访问nativeElement
属性时,它是undefined
.
下面是片段.
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);
}
}
请看一下plunk美元.