Search code examples
angulartypescriptviewchild

Get async data via @ViewChild


There is a component Child that makes an API request and gets some async data. This data is stored to the property count.

There is a component Parent that needs to get count value once it's gotten and do some actions with it.

ParentComponent.ts

@ViewChild('child', {static: false}) child: ChildComponent;
...
ngAfterViewInit() {
    this.number = this.child.count;
}
...

Question

Since the count property is async, inside ngAfterViewInit() I receive undefined. How to get updated value? Maybe ngOnChanges() or something else should work for me?


Solution

  • The reason you're getting undefined is that you're expecting the value before the async data is made available (when your async request has finished I assume). You can use an Event Emitter to send the data to the parent. This way, you can set number in the parent to be the value of count only when you have it. I also recommend reading the Component Interaction guide in the official docs.

    1. Register the event emitter in your child component

    ChildComponent

    @Output() countChanged: EventEmitter<any> = new EventEmitter();
    
    
    1. When you receive the data, you can emit the data to the parent:
    // ...Logic that gets the data
    this.countChanged.emit(this.count);
    //...
    
    1. In the parent template, you can then bind to the child component and listen to child events.

    Parent Component HTML

    <child-component (countChanged)="doSomethingWithCount($event)></child-component>`
    

    Parent Component

    public doSomethingWithCount(count: number):void {
        this.number = count;
        //. . . More logic
    }