Angular:nativeElement 在 ViewChild 上未定义

标签 angular

我想使用 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 属性。

Plunker example

关于Angular:nativeElement 在 ViewChild 上未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45921819/

相关文章:

json - Nativescript中如何显示Json数据

angular - 从Linux创建ASP.NET Core 3.0 Angular Web应用程序镜像

javascript - 如何在 Angular 7 中使用 + 号验证国家代码?

angular - ng2 stomp 客户端 unsubscribe() 不起作用

javascript - 在模板 ANGULAR5 中显示数据(对象)的最佳方式

javascript - 如何更改事件上的按钮颜色?

Angular 2。我可以同时使用 ViewChild 和 @Input 吗?

javascript - 为什么 Angular 2 无法检测到变化?

javascript - 单击 Angular 4 应用程序中的 SVG 元素时调用函数

css - 在 Angular 2 中动态更新 css