在使用 ViewChild 绑定模板变量之前,确保 ngIf 指令已经解析,因为如果 ngIf 中的条件为 false,那么绑定的元素就会被移除,ViewChild 也就无法找到这个元素了。有两种方法可以解决这个问题:
// 错误示范 @ViewChild('myElement') myElement: ElementRef;
// 解决方法1 ngAfterViewChecked() { this.myElement = this.myElementRef.nativeElement; }
// 解决方法2