Getting undefined nativeElement when using @viewchid with *ngIf condition
Error
Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'nativeElement')
CodePudding user response:
@ViewChild('myElement', { static: false }) myElement: ElementRef<HTMLElement>;
Don't call it in the constructor, ngAfterViewInit
is the first hook to have it defined.
CodePudding user response:
If your `*ngIf condition is dynamic you should probably use a setter.
@ViewChild('myElement') set setMyElement(myElement: ElementRef) {
if (myElement) {
// Here you can access content.nativeElement etc.
}
}