Angular:ViewChild上的nativeElement未定义

65
我想使用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
1个回答

156

如果您想获取托管组件或指令的元素引用,您需要明确指定您想要的是元素而不是组件或指令。

@ViewChild('alert', { read: ElementRef }) alert:ElementRef;

另请参见angular 2 / typescript:在模板中获取元素

在您的情况下,我猜您需要两个不同的@ViewChild(),一个用于组件引用以便访问show()方法,另一个用于访问DOM属性。

Plunker示例


谢谢!默认情况下,它返回组件实例。我如何明确指定“read”属性以返回组件实例?此外,如果您能告诉我可以为不同目的设置哪些其他值,那将是很棒的。 - karthikaruna
3
如果它是一个普通的HTML元素,那么默认为ElementRef,如果它托管了一个组件或指令,你将默认得到该组件实例。你只需要使用组件或指令的类型名称来请求特定的组件或指令,例如 @ViewChild('alert', { read: AlertComponent }) alert: AlertComponent; - Günter Zöchbauer
4
也适用于ViewChildren - Lahiru Chandima
18
在 Angular 8 中,您需要将静态选项(现在是必需的)设置为 false。@ViewChild('alert', { read: ElementRef, static:false }) 否则,它将无法工作。 - alchi baucha
6
实际上{static: false}是默认设置。现在需要{read: ElementRef}来使其正常工作。文档中完全没有提到这一点,似乎这是一个非常重大的破坏性变更。 - Neutrino
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接