【问题标题】:Typescript Error "Cannot read property 'nativeElement' of undefined"?打字稿错误“无法读取未定义的属性'nativeElement'”?
【发布时间】:2021-10-18 20:25:01
【问题描述】:

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

无法读取未定义的属性“nativeElement”

我正在使用 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吗?我假设它的 ViewChild?另外,你可以试试这样const firstOcc = this.editElem?.nativeElement.querySelector&lt;HTMLElement&gt;('.highlighted')
  • 没错,添加了代码
  • this.editElem 未定义。如果您不希望出现错误,请在尝试获取其属性之前检查它是否未定义。
  • 这能回答你的问题吗? Detecting an undefined object property
  • 您也可以分享您的 HTML 代码吗?也许有什么问题。我想我知道确切的问题,但我需要先查看您的代码@ParitoshM

标签: angular typescript undefined queryselector typescript-eslint


【解决方案1】:

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

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

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

  
    }
  }

【讨论】:

    【解决方案2】:

    我敢打赌,您的 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>
    

    这意味着突出显示的类在#term(div) 中。它应该像那样工作。

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 2021-12-03
      • 2018-07-18
      • 1970-01-01
      • 2017-12-15
      • 2017-09-28
      • 1970-01-01
      • 2017-07-21
      • 2019-08-04
      相关资源
      最近更新 更多