0

I'm tryng to get a DOM Element in Angular, console throws error: core.js:5882 ERROR TypeError: Cannot read property 'nativeElement' of undefined. If i go to another route and then go back i can see the correct element in console, but if i load the page at the first time it throws error, how can i solve this? The element i'm trying to get is nested by a div with *ngIf that evaluates an asynchronous variable. Thanks in advance

@ViewChild('inputSearch') el: ElementRef;

ngAfterViewInit(){
   console.log(this.el.nativeElement);
}
<div *ngIf="asynchronous variable">
   <input type="text" #inputSearch >
</div>
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • Are you sure that this code shipped you posted is what you wanted to ask? I tried minimal angular project and it seems to be working just fine. https://stackblitz.com/edit/angular-ivy-re9w8f?file=src%2Fapp%2Fapp.component.ts – tprieboj Nov 29 '20 at 16:13
  • My guessing is that your condition `
    ` is different in your application therefore it is possible that your `input` is not rendered when `ngAfterViewInit` is called.
    – tprieboj Nov 29 '20 at 16:20
  • in my code *ngIf evaluates an asynchronous value – sonEtLumiere Nov 29 '20 at 16:22
  • So there is like 99% chance that your input is not rendered yet. You should update your question :) – tprieboj Nov 29 '20 at 16:24

1 Answers1

0

You can check it after the content is checked.

ngAfterContentChecked() {
    console.log(this.el.navtiveElement);
}
// Don't forget to implement the Interface in your component.
class SomeComponenet implements OnInit, AfterContentChecked {
    ...
}