这个角度 应用程序仅由具有单个<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;
问:为什么ngOnInit和constructor函数都记录div_a是未定义的?如何解决这些函数不能使用div_a对象的问题?
下面是到Stackblitz项目的链接(请注意,链接到这个GitHub项目的stackblitz分支需要从master切换到qViewChild分支)。
https://stackblitz.com/edit/angular-r9hwbs?file=src%2Fapp%2Fwidget-a%2Fwidget-a.component.html

发布于 2020-02-05 00:40:45
基于文档,ViewChild和ViewChildren查询在AfterViewInit之前运行,因此您需要在那里访问它们。只访问div_a是行不通的,除非您在模板中标记它。
除其他外,你可以接触的儿童包括:
<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}
}
}发布于 2020-02-05 00:44:41
使用@ViewChild时,不要使用ngOnInit或构造函数,因为它尚未加载。使用ngAfterViewInit()
https://stackoverflow.com/questions/60067416
复制相似问题