Search code examples
angulartypescriptundefinedqueryselectortypescript-eslint

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


I have tried solutions present on Stack Overflow but none of them is working for me. I am getting the following error from a TypeScript file

Cannot read property 'nativeElement' of undefined

I am using Angular ngAfterViewInit lifecycle hook

I have discovered I am getting error at line const firstOcc = this.editElem.nativeElement.querySelector<HTMLElement>('.highlighted');

Below is my code

@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);

  
}

Solution

  • Try this... check if the editElem is defined first:

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