I am facing a challenge passing Async data from child to parent component. When I try to access console.log(this.values)
within the ngAfterViewInit()
method in the parent component's HTML page load, it returns an empty value. However, upon clicking the apply button in the child component, an event is emitted and the console.log(this.values);
inside the getValues($event)
method successfully prints the values.
Below is my parent component .ts file:
name = 'ViewUI';
@ViewChild('ChildValues', { static: false }) childReference: ChildComponent;
ngAfterViewInit() {
this.values = this.childReference.this.responseValues;
console.log(this.values);
mapResponse(this.values);
}
In this case, `mapResponse(this.values)` method runs before the data is retrieved from `this.values` in the child component.
getValues($event) {
this.values = $event;
console.log(this.values);
this.apply();
}
This is my parent component .html file:
<app-child #ChildValues (getEvent)=" getValues($event)" [name]="name"></app-child>
Here is my child component .html file:
<button (click)="applyResponses()" mat-raised-button>
Apply
</button>
And lastly, here is my Child component .ts file:
export class ChildComponent implements OnInit {
responseValues = {
names: [], ages: []
};
@Output() getEvent = new EventEmitter < any > ();
@Input() name: string;
ngOnInit() {
this.getNames();
this.getAges();
console.log(this.name);
}
getNames() {
this.apiService.getnames(Id).subscribe((names) => {
this.responseValues.names = [names[0].name];
});
}
getAges() {
this.apiService.getages(Id).subscribe((ages) => {
this.responseValues.ages = [ages[0].age];
});
}
applyResponses() {
this.getEvent.emit(this.responseValues);
console.log(this.responseValues);
}
}
Any ideas on how to retrieve data from the child to the parent component during the parent page load?