0

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

  
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Paritosh M
  • 289
  • 2
  • 5
  • 16
  • Can you share what is editElem? I'm assuming its ViewChild? Also, you can try like this `const firstOcc = this.editElem?.nativeElement.querySelector('.highlighted')` – amnah Aug 16 '21 at 20:19
  • Thats right, added code – Paritosh M Aug 16 '21 at 20:20
  • `this.editElem` is undefined. If you don't want the error, check if it's undefined before trying to get properties on it. – Heretic Monkey Aug 16 '21 at 20:32
  • Does this answer your question? [Detecting an undefined object property](https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) – Heretic Monkey Aug 16 '21 at 20:33
  • Can you please share your HTML code too? maybe there's something wrong. I think I know the exact problem but I need to see your code first @ParitoshM – MeDead Aug 16 '21 at 20:34
  • @ParitoshM I tried it here https://stackblitz.com/edit/angular-8-viewchild-example-d2y3kh?file=src%2Fapp%2Fapp.component.html Can you kindly update with yout HTML as well. – amnah Aug 16 '21 at 20:38

2 Answers2

0

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

  
    }
  }
DJ Burb
  • 2,346
  • 2
  • 29
  • 38
0

I bet you got something like this in your HTML. If your uploading your HTML I can show you an example with your code.

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

or

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

but you need to use it like this

<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>

so that means the highlighted class is in the #term(div). It should work like that.

Hopefully that will help you.

MeDead
  • 197
  • 2
  • 9