我想使用
ViewChild
访问组件的DOM。但是当我尝试访问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。
ElementRef
,如果它托管了一个组件或指令,你将默认得到该组件实例。你只需要使用组件或指令的类型名称来请求特定的组件或指令,例如@ViewChild('alert', { read: AlertComponent }) alert: AlertComponent;
。 - Günter ZöchbauerViewChildren
。 - Lahiru Chandima@ViewChild('alert', { read: ElementRef, static:false })
否则,它将无法工作。 - alchi baucha{static: false}
是默认设置。现在需要{read: ElementRef}
来使其正常工作。文档中完全没有提到这一点,似乎这是一个非常重大的破坏性变更。 - Neutrino