我想使用 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 .
最佳答案
如果你想获取托管组件或指令的元素的引用,你需要指定你想要的是元素而不是组件或指令
@ViewChild('alert', { read: ElementRef }) alert:ElementRef;
另见 angular 2 / typescript : get hold of an element in the template
在你的情况下,我猜你需要两个不同的 @ViewChild()
一个用于组件引用能够访问 show()
方法,另一个是能够访问 DOM 属性。
关于Angular:nativeElement 在 ViewChild 上未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45921819/