javascript - How to pass data from parrent constructor to child component in angular 2 -
i have angular 2 page need show 2 different components using same array of data external api. parent regular component, , child shared among several other components using same functionality.
in parent component class have output property declared:
public weatherlist: weatherforecast[]; @output() public weatherlistdata: any; inside constructor of parent component, populate weatherlistdata property data external api
http.get(url) .subscribe(result => { this.weatherlist= result.json() weatherforecast[]; this.weatherlistdata = this.weatherlist; }); and i'm using inside parent template success, like: {{ weatherlist.somevalue }}
also, inside parent component template, have call child component
<daily-temperature-chart [weatherlistdata]='weatherlistdata'></daily-temperature-chart> in child component class have declared property
@input() weatherlistdata: any; but, when try access weatherlistdata property in constructor, or init of child component, undefined result.
edit: have played console.log() , noticed child component constructor , oninit() methods return before http.get() parent component. maybe problem, i'm still new angular , can't tell.
can point me how solve this?
you've service call can't go constructor or oninit because component initialization not dependent on service call situation angular provides onchanges whenever input value updated onchanges fired.
ngonchanges(changes: any){ console.log(changes); console.log(this.weatherlistdata); } onchanges passes argument informs current state , pervious state able use input values. if components bases on input , input based on other operation can handle in block.
Comments
Post a Comment