I\'ve looked at several related posts and documentation, but still can\'t seem to get expected behavior from @ViewChild.
Ultimately, I\'m trying to set the scroll p
Sometimes, if the component isn’t yet initialized when you access it, you get an error that says that the child component is undefined.
However, even if you access to the child component in the AfterViewInit, sometimes the @ViewChild was still returning null. The problem can be caused by the *ngIf or other directive.
The solution is to use the @ViewChildren instead of @ViewChild and subscribe the changes subscription that is executed when the component is ready.
For example, if in the parent component ParentComponent you want to access the child component MyComponent.
import { Component, ViewChildren, AfterViewInit, QueryList } from '@angular/core';
import { MyComponent } from './mycomponent.component';
export class ParentComponent implements AfterViewInit
{
//other code emitted for clarity
@ViewChildren(MyComponent) childrenComponent: QueryList;
public ngAfterViewInit(): void
{
this.childrenComponent.changes.subscribe((comps: QueryList) =>
{
// Now you can access the child component
});
}
}