我想使用访问组件的DOM ViewChild.但是当我试图访问该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);
}
}
Run Code Online (Sandbox Code Playgroud)
请看看插头.
Gün*_*uer 46
如果要获取承载组件或指令的元素的引用,则需要指定您希望元素而不是组件或指令
@ViewChild('alert', { read: ElementRef }) alert:ElementRef;
Run Code Online (Sandbox Code Playgroud)
另请参见angular 2/typescript:获取模板中的元素
在你的情况下,我猜你需要两个不同@ViewChild()的组件引用才能访问该show()方法,第二个能够访问DOM属性.
| 归档时间: |
|
| 查看次数: |
15638 次 |
| 最近记录: |