javascript - 如何正确使用ViewChild

标签 javascript angular typescript

This Angular app仅包含 app-root具有单个 <div> 的组件和一个 <button> .

单击按钮时 onClick()功能日志来控制台 div_a对象:

console.log("...onClick() div_a:", this.div_a);

div_a用以下语句定义:

@ViewChild('div_a', { static: false }) div_a: Component;

问题:为什么 ngOnInitconstructor函数记录 div_a是未定义的?如何解决这些功能无法使用的问题div_a对象?

下面是 Stackblitz 项目的链接(请注意,链接到此 stackblitz 项目的 GitHub 分支需要从 master 切换到 qViewChild 分支)。

https://stackblitz.com/edit/angular-r9hwbs?file=src%2Fapp%2Fwidget-a%2Fwidget-a.component.html

enter image description here

最佳答案

基于docs , ViewChildViewChildren查询在 AfterViewInit 之前运行,因此您需要在那里访问它们。刚刚访问 div_a除非您在模板中标记它,否则它将不起作用。

您可以访问的子项包括:

  • 任何带有 @Component 或 @Directive 装饰器的类
  • 字符串形式的模板引用变量(例如使用 @ViewChild('cmp') 查询 <my-component #cmp></my-component>)

所以你需要这样的东西:

<p #myPara>
  Start editing to see some magic happen :)
</p>
import { Component, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit  {
  @ViewChild('myPara', {static: false}) paragraph;


  ngAfterViewInit() {
    console.log(this.paragraph) // results in -> ElementRef {nativeElement: p}
  }
}

Blitz

关于javascript - 如何正确使用ViewChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60067416/

相关文章:

javascript - 为每个td添加事件监听器

单击按钮时显示 DIV 容器的 Javascript 函数

javascript - 如何在 CRM 2013 文本字段中指定格式

typescript - 每次在 Angular 2 中选择一个新选项时如何触发一个函数?

regex - ng build 由于 regExp 而给出错误

javascript - Node中并行/异步的多个分页GET API调用

javascript 函数第二次不工作

html - 如何在 Angular 形 Material 中居中垫卡?

Angular 替换方法不适用于字符串

javascript - 如何使用 nestfastify 编写来自 nestjs 异常过滤器的响应