Angular 8 viewChild returns undefined

I had a similar problem where ViewChild component is undefined in onInit() method.

This fixed the issue:

// Ensure Change Detection runs before accessing the instance
@ContentChild('foo', { static: false }) foo!: ElementRef;

// If you need to access it in ngOnInit hook
@ViewChild(TemplateRef, { static: true }) foo!: TemplateRef;

Leave a Comment