Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way I can pass dynamic data to a component in Angular?

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?

like image 489
Ravi Yadav Avatar asked Dec 07 '17 12:12

Ravi Yadav


1 Answers

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);
}
like image 164
Bohdan Khodakivskyi Avatar answered Nov 15 '22 06:11

Bohdan Khodakivskyi