在ViewChild上未定义nativeElement

在ViewChild上未定义nativeElement

本文介绍了角度:在ViewChild上未定义nativeElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to access the DOM of a component using ViewChild. But when I try to access the nativeElement property, it's 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 .

推荐答案

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

If you want to get a reference of an element that hosts a component or directive you need to specify that you want the element instead of the component or directive

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

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

在您的情况下,我想您需要两个不同的@ViewChild()组件引用才能访问show()方法,第二个要访问DOM属性.

In your case I guess you need two different @ViewChild() one for the component reference to be able to access the show() method, and a 2nd one to be able to access DOM attributes.

柱塞示例

这篇关于角度:在ViewChild上未定义nativeElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:11