onedevteam.com
onedevteam.com

Reputation: 4178

How to pass data from parrent constructor to child component in angular 2

I have a angular 2 page where i need to show 2 different components using same array of data from external API. Parent is regular component, and child is shared among several other components using same functionality.

In parent component class i have output property declared:

public weatherList: WeatherForecast[];
@Output() public weatherListData: any;

Inside constructor of parent component, i populate weatherListData property with data from an external API

    http.get(url)
        .subscribe(result => {
            this.weatherList= result.json() as WeatherForecast[];
            this.weatherListData = this.weatherList;
        });

and i'm using it inside parent template with success, something like: {{ weatherList.someValue }}

Also, inside parent component template, i have a call to a child component

<daily-temperature-chart [weatherListData]='weatherListData'></daily-temperature-chart>

In child component class i have declared property

@Input() weatherListData: any;

but, when i try to access weatherListData property in constructor, or init of child component, i get undefined result.

EDIT: I have played with console.log() and noticed that child component Constructor and OnInit() methods return before http.get() from parent component. Maybe this is problem, but i'm still new to angular and can't tell.

Can someone point me how to solve this?

Upvotes: 1

Views: 1253

Answers (1)

Babar Hussain
Babar Hussain

Reputation: 2905

You've a service call so you can't go for constructor or OnInit because component initialization is not dependent on your service call for this situation angular provides OnChanges whenever your input value is updated OnChanges fired.

 ngOnChanges(changes: any){
  console.log(changes);
  console.log(this.weatherListData);
 }

OnChanges passes as well an argument which informs about the current state and pervious state now you are able to use input values. If your components are bases on input and input is based on any other operation you can handle it in this block.

Upvotes: 1

Related Questions