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;
问题:为什么 ngOnInit
和constructor
函数记录 div_a
是未定义的?如何解决这些功能无法使用的问题div_a
对象?
下面是 Stackblitz 项目的链接(请注意,链接到此 stackblitz
项目的 GitHub 分支需要从 master
切换到 qViewChild
分支)。
https://stackblitz.com/edit/angular-r9hwbs?file=src%2Fapp%2Fwidget-a%2Fwidget-a.component.html
最佳答案
基于docs , ViewChild
和ViewChildren
查询在 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}
}
}
关于javascript - 如何正确使用ViewChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60067416/