我想使用ViewChild访问组件的DOM.但当我try 访问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相关问答推荐

Angular material 输入字段中的图标未显示

从嵌套组件导航到命名路由中的顶级路由

在状态更新后是否会再次触发ngrx效果?

Angular 17@在大小写时切换多个值

声明Angular material 中按钮的自定义 colored颜色

成Angular 的嵌套router-outlet

ANGLING:ExpressionChangedAfterChecked在嵌套形式中由子项添加验证器

如何使用来自不同可观测对象的值更新可观测对象

使用 TAB 键时如何聚焦mat-select组件?

Angular CLI 与 Angular 版本不兼容

升级到 Ng 16 - npm 错误!对等依赖冲突:@angular/compiler-cli@16.2.1

获取 Angular 中所有子集合 firestore 的列表

从组件调用时服务中的 AddTodo 方法不起作用

如何访问父组件中提供的 TemplateRef 内的服务?

在一个组件中创建多个表单

Angular 4:InvalidPipeArgument:管道AsyncPipe的[object Object]

Angular 2 可用的 yeoman 生成器

如何在 Angular 5 react式表单输入中使用管道

从 Angular 中的自定义表单组件访问 FormControl

如何在 Angular Material 中设置图标的 colored颜色 ?