在Angular 8中,@ViewChild装饰器用于获取对模板视图中的子组件或DOM元素的引用。如果@ViewChild返回undefined,可能有以下几个原因:
尝试在ngOnInit生命周期钩子函数之前访问@ViewChild。在ngOnInit之前,视图还没有完全初始化,因此无法找到对应的子组件或DOM元素。将访问@ViewChild的代码移动到ngAfterViewInit生命周期钩子函数中可以解决此问题。
在模板中没有正确使用指令或组件选择器。确保在模板中正确使用了指令或组件选择器,并且它们被正确地渲染到了视图中。
下面是一个示例,展示了如何解决@ViewChild返回undefined的问题:
组件代码:
import { Component, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-child',
template: 'Child Component'
})
export class ChildComponent {}
@Component({
selector: 'app-parent',
template: ' '
})
export class ParentComponent implements AfterViewInit {
@ViewChild('childElement', { static: false }) childElement;
ngAfterViewInit() {
console.log(this.childElement); // 输出正确的DOM元素
}
}
在上面的示例中,父组件(ParentComponent)使用@ViewChild装饰器获取子组件(ChildComponent)中的DOM元素的引用。ngAfterViewInit生命周期钩子函数确保在视图完全初始化之后才访问@ViewChild。
希望这可以帮助到你解决@ViewChild返回undefined的问题。