繁体   English   中英

Angular:在ViewChild上未定义nativeElement

[英]Angular: nativeElement is undefined on ViewChild

我想使用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);
  }
}

请看看插头

如果要获取承载组件或指令的元素的引用,则需要指定您希望元素而不是组件或指令

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

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

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

Plunker的例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM