Home > database >  Angular set dynamic bar chart data and labels
Angular set dynamic bar chart data and labels

Time:09-30

I'm trying to dynamically add data to my bar chart data set but the problem it keeps saying undefined. So i'll show the current working version.

public barChartData: ChartDataSets[] = [
{ data: [], label: 'High' },
{ data: [], label: 'Medium' },
{ data: [], label: 'Low' }
];

this.barChartData[0].data.push(2);
console.log(this.barChartData[0].label);
console.log(this.barChartData[0].data);

This works but it's fixed. The problem is i dont know how many data there will be. So i tried this way.

public barChartData: ChartDataSets[] = [];
public barChartDataCount = 0;

for (let index = 0; index < this.tag.length; index  ) {
  if(this.tag[index].type=='type')
  {
    this.barChartData[this.barChartDataCount].label=this.tag[index].name;
    this.barChartData[this.barChartDataCount].data.push(2);
    this.barChartDataCount  ;
    this.numType  ;
  }
}

And the error i got is ERROR TypeError: Cannot set properties of undefined (setting 'label')

CodePudding user response:

this.barChartData is defined as empty array in the beginning. So when you try to access its first element by writing this.barChartData[this.barChartDataCount] , it returns null as array is empty.

You should try to push items into your array like this

for (let index = 0; index < this.tag.length; index  ) {
  if(this.tag[index].type=='type')
  {
    this.barChartData.push({
        label: this.tag[index].name,
        data: 2
    })
    // other logic
  }
}

  • Related