打字稿错误 "Cannot read property 'nativeElement' of undefined"?

Typescript Error "Cannot read property 'nativeElement' of undefined"?

我已经尝试过 Stack Overflow 上的解决方案,但 none 对我有用。我从 TypeScript 文件中收到以下错误

Cannot read property 'nativeElement' of undefined

我正在使用 Angular ngAfterViewInit 生命周期钩子

我发现我在第 const firstOcc = this.editElem.nativeElement.querySelector<HTMLElement>('.highlighted');

行遇到错误

下面是我的代码

@ViewChild('term',{ static: false }) editElem!: ElementRef<HTMLTableDataCellElement>;

ngAfterViewInit() {
  console.log('Error at below line')
  const firstOcc = this.editElem.nativeElement.querySelector<HTMLElement>('.highlighted');

  if (!firstOcc) {return;}
  changeDisplay(firstOcc);

  
}

试试这个...检查是否首先定义了 editElem:

ngAfterViewInit() {
  console.log('Error at below line')
  if(this.editElem)
  {
       const firstOcc = this.editElem.nativeElement.querySelector<HTMLElement> 
       ('.highlighted');

     if (!firstOcc) {return;}
     changeDisplay(firstOcc);

  
    }
  }

我打赌你的 HTML 里有这样的东西。如果你上传你的 HTML 我可以用你的代码给你看一个例子。

<hello  name="{{ name }}"></hello>
<p class="highlighted">
  Start editing to see some magic happen :)
</p>

<hello #term name="{{ name }}"></hello>
<p class="highlighted">
  Start editing to see some magic happen :)
</p>

但你需要这样使用它

<hello name="{{ name }}"></hello>

<div #term> #term <--- for the ViewChild

  <div class="highlighted">asdasd</div> <---- class highlighted
  Start editing to see some magic happen :)
</div>

所以这意味着突出显示的 class 在 #term(div) 中。它应该是这样工作的。

希望对你有所帮助。