8
votes

I have two component in my angular 2 application : component A (parent) and component B (child).

When i passe data (myData) from A to B with @Input() i get my data in my B (child component), but the problem is that the child component loads BEFORE myData and i got indefined, the only way a can console.log(myData) is in ngOnDestroy hook !

How to deal with this kind of load order ?

3
try to load the data in the constructor of the component - rashfmnb
It's unclear why this causes problems. You can use the lifecycle hooks ngOnChanges() which is called every time the @Input() is updated from the outside. ngOnInit() is called after the first time ngOnChanges() is called. If that doesn't work then please provide more code that demonstrates what you try to accomplish. I can't now what's going on on your site without seeing the code. - Günter Zöchbauer

3 Answers

11
votes

Here is a solution that was easiest for me. Use *ngIf in your parent component to delay the initialization of the child component. You will bind the child component only if myData has a value.

<parent-component>
  <child-component [input]="myData" *ngIf="myData"></child-component>
</parent-component>
7
votes

You can simply use a *ngIf in your parent like

< child-component *ngIf="myData" > </child-component>
-2
votes

You can find good example to do it in example project here.

Check app.service.ts code.

You need to describe global service that will store your data that will be shared between components.