【问题标题】:Angular: nativeElement is undefined on ViewChildAngular:ViewChild 上未定义 nativeElement
【发布时间】:2018-02-05 21:21:25
【问题描述】:

我想使用ViewChild 访问组件的DOM。但是当我尝试访问nativeElement 属性时,它是undefined

下面是sn-p。

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

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    另见angular 2 / typescript : get hold of an element in the template

    在你的情况下,我猜你需要两个不同的 @ViewChild() 一个用于组件引用以能够访问 show() 方法,而第二个则能够访问 DOM 属性。

    Plunker example

    【讨论】:

    • 谢谢!默认情况下,它返回组件实例。如何显式指定 read 属性以返回组件实例?另外,如果您能说出我可以为不同目的设置的其他值是什么,那就太好了。
    • 如果是纯 HTML 元素,默认为ElementRef,它承载一个组件或指令,默认情况下您将获取组件实例。您可以只使用组件或指令的类型名称来请求特定的名称,例如 @ViewChild('alert', { read: AlertComponent }) alert: AlertComponent;
    • 也适用于ViewChildren
    • 在 Angular 8 中,您必须将静态选项(现在是强制性的)设置为 false。 @ViewChild('alert', { read: ElementRef, static:false }) 不然不行。
    • 其实{static: false}是默认的。现在需要{read: ElementRef} 才能使其正常工作。在文档中没有提及它似乎是一个巨大的破坏性变化。
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2022-08-20
    • 2018-02-26
    • 2017-12-15
    • 2017-09-28
    相关资源
    最近更新 更多