I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.
ParentComponent.ts
results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}
ParentComponent.html
<app-childComponent [dataNeeded]=results></app-childComponent>
ChildComponent.ts
@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
console.log(dataNeeded); //Always undefiend
}
So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?
You might try OnChanges lifecycle hook method.
In your case, you would need to add it to your child component like so:
ngOnChanges(changes) {
if (changes['dataNeeded'] && this.dataNeeded) {
console.log(this.dataNeeded);
}
}
PS Also I just noticed the wrong syntax in your ChildComponent.ts
, it is missing this
:
ngOnInit() {
console.log(this.dataNeeded);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With