出现"Angular 8的viewChild返回undefined"的问题通常是因为使用了视图初始化之前尝试访问ViewChild的属性。解决这个问题的方法是使用ngAfterViewInit钩子来确保视图已经初始化完毕。下面是一个包含代码示例的解决方法:
component.ts文件:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-example',
template: 'Hello World!'
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('myDiv', {static: false}) myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.textContent); // 访问ViewChild
}
}
在上面的示例中,我们使用了AfterViewInit钩子来确保视图已经初始化完毕。在ngAfterViewInit方法中,我们可以访问到ViewChild的属性,并打印出其textContent。
请注意,在@ViewChild装饰器中,我们将第二个参数设置为{static: false}。这是因为在Angular 8中,默认情况下,ViewChild在ngOnInit之前不会被初始化。通过将static设置为false,我们可以确保在ngAfterViewInit之前,ViewChild已经被初始化。
希望以上解决方法可以帮助你解决问题。