Sebastian Ebner Sebastian Ebner - 4 months ago 76
TypeScript Question

Angular2, ng2-chart child rendering before parent

I am currently working on a visualization application with

Angular2
and
TypeScript
for the
frontend
and Spring-Boot for the
backend
. Now I am at the point where the data coming from the
backend
hast to be displayed in my ng2-chart components.

I am loading the data in my parent components ngOnInit() function. The data is pushed to two arrays which work as input for my child component like so:

ngOnInit() {
this._sqlService.getCubeErrors().subscribe(
data => {
for (var i = 0; i < data.length; i++) {
this.barLabels.push(data[i]["monthCube"]);
this.barData[0]["data"].push(data[i]["errors"]);
}
},
err => { this.error = true }
)
}


and here my service:

getCubeErrors() {
return this.http.get('/rest/cubeerrors').map((res: Response) => res.json());
}


The two arrays
barLabels
and
barData
are passed on to the child component like this:

<bar-chart [barLabels]="barLabels" [barData]="barData" ></bar-chart>


In my child component i am using them to create a chart:

@Input() barData: any[];
@Input() barLabels: Array<string>;

public barChartData: any[] = this.barData;
public barChartLabels: string[] = this.barLabels;


I tried to track the data with some console.log() breakpoints and it seems that they are the same.

The problem I am facing is, that somehow the chart of the child component is rendered before the
ngOnInit()
takes place and so my data is not displayed.
I was searching for a update function of some sort but wasn't successful.

I hope someone might have an answer for this,

Sebastian

Answer

@Arpit is correct - you should use ngOnChanges instead of ngOnInit for anything that relies on the data being passed to it through it's @Inputs.

So your child component would be very similar, just it would have an ngOnChanges function which checks that the @Inputs have been fetched before trying to use them.

@Input() barData: any[];
@Input() barLabels: Array<string>;

public barChartData: any[];
public barChartLabels: string[];

ngOnChanges(){
    if(this.barData && this.barLabels){
        this.barChartData = this.barData;
        this.barChartLabels = this.barLabels;

        //Do anything else that relies on these arrays being defined.
    }
}

Here is the documentation.

Comments