Angular:在ViewChild上未定义nativeElement

kar*_*una 23 angular

我想使用访问组件的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属性.

Plunker的例子

  • 在 Angular 8 中,您必须将 static 选项(现在是强制的)设置为 false。`@ViewChild('alert', { read: ElementRef, static:false })` 否则,它将不起作用。 (11认同)
  • 实际上 `{static: false}` 是默认值。现在需要“{read: ElementRef}”才能使其正常工作。文档中没有提及这似乎是一个巨大的破坏性更改。 (6认同)
  • 也适用于“ViewChildren” (3认同)
  • 如果它是纯HTML元素,则默认值为`ElementRef`,它承载一个组件或指令,默认情况下,您将获得该组件实例。您可以只使用组件或指令的类型名称来请求特定的名称,例如`@ViewChild('alert',{read:AlertComponent})alert:AlertComponent;。 (2认同)