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?
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.
ChildComponent
@Output() countChanged: EventEmitter<any> = new EventEmitter();
// ...Logic that gets the data
this.countChanged.emit(this.count);
//...
Parent Component HTML
<child-component (countChanged)="doSomethingWithCount($event)></child-component>`
Parent Component
public doSomethingWithCount(count: number):void {
this.number = count;
//. . . More logic
}