首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确使用ViewChild

如何正确使用ViewChild
EN

Stack Overflow用户
提问于 2020-02-05 00:27:56
回答 2查看 4.2K关注 0票数 1

这个角度 应用程序仅由具有单个<div><button>app-root组件组成。

当单击按钮时,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项目的链接(请注意,链接到这个GitHub项目的stackblitz分支需要从master切换到qViewChild分支)。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-05 00:40:45

基于文档ViewChildViewChildren查询在AfterViewInit之前运行,因此您需要在那里访问它们。只访问div_a是行不通的,除非您在模板中标记它。

除其他外,你可以接触的儿童包括:

  • 具有@组件或@指令装饰符的任何类
  • 作为字符串的模板引用变量(例如,使用@ViewChild(‘cmp’)查询<my-component #cmp></my-component> )

所以你需要这样的东西:

代码语言:javascript
复制
<p #myPara>
  Start editing to see some magic happen :)
</p>
代码语言:javascript
复制
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}
  }
}

闪电战

票数 6
EN

Stack Overflow用户

发布于 2020-02-05 00:44:41

使用@ViewChild时,不要使用ngOnInit或构造函数,因为它尚未加载。使用ngAfterViewInit()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60067416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档