I have a parent component which is getting data from a server through a service. I need some of this data to be passed to the Child component.
I\'ve been trying to p
At the time your ChildComponent (you called it also ParentComponent, but i guess it's a typo) gets initialized and executes its ngOnInit, there is no data in your parent avaible since your service will still be out getting your data. Once your data is there it will be pushed to the child.
What you can do depends on your usecase..
If you just want to display the data in your ChildComponent template, you could use the elvis operator (?). Something like: {{ childData?}} or {{ childData?.myKeyName }}...
If you want to do some other stuff, you may use a setter in your ChildComponent. It will intercept the input change and give you the opportunity to alter/test/"do what ever you want" with it before you do other things with it in your ChildComponent.. eg.:
@Component({
selector: 'test-child',
template: `
`
})
export class ChildComponent implements OnInit {
private _childData: any;
@Input()
set childData(parentData: any) {
// every time the data from the parent changes this will run
console.log(parnetData);
this._childData = parentData; // ...or do some other crazy stuff
}
get childData(): any { return this._childData; }
ngOnInit() {
// We don't need it for that...
}
}
or use ngOnChanges as Madhu mentioned.
You also might want to take a look at the cookbook entry for Component Communication in the official docs.