我尝试在Angular中获取DOM元素,控制台抛出错误: core.js:5882 ERROR TypeError: Cannot read property 'nativeElement‘of undefined。如果我转到另一个路由,然后返回,我可以在控制台中看到正确的元素,但如果我在第一次加载页面时抛出错误,我如何解决这个问题?我尝试获取的元素是由一个带有*ngIf的div嵌套的,该div计算一个异步变量。提前感谢
@ViewChild('inputSearch') el: ElementRef;
ngAfterViewInit(){
console.log(this.el.nativeElement);
}<div *ngIf="asynchronous variable">
<input type="text" #inputSearch >
</div>
发布于 2020-11-30 00:16:36
你可以在content is checked之后检查它。
ngAfterContentChecked() {
console.log(this.el.navtiveElement);
}// Don't forget to implement the Interface in your component.
class SomeComponenet implements OnInit, AfterContentChecked {
...
}https://stackoverflow.com/questions/65062123
复制相似问题