George Edwards George Edwards - 1 month ago 12
Javascript Question

Creating dynamic arrays in Angular2

I am building a chart.js function in my angular2 web application. I want the bars in a bar chart to be red or green depending if their value is above or below a certain threshold. At the moment, I have a static solution which looks like this:

public barChartLabels: string[] = ['06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00', '03:00', '04:00', '05:00'];
public barChartType: string = 'bar';
public barChartLegend: boolean = false;

public barChartData: any[] = [
{
data: [85, 81, 80, 81, 56, 73, 70, 5, 0, 0, 65, 70, 83, 90, 85, 86, 84, 80, 87, 88, 82, 74, 71, 80],
label: 'Values'
}
];
private colors = [
{
backgroundColor: [
'rgba(45, 227, 81, 0.2)',
'rgba(45, 227, 81, 0.2)',
'rgba(45, 227, 81, 0.2)',
'rgba(45, 227, 81, 0.2)',
'rgba(45, 227, 81, 0.2)',
'rgba(45, 227, 81, 0.2)'
// Potentially loads more colors
]
}
];


However, this is messy and feels like overkill. I need a solution which will support the dynamic update of my data and simply compare the value to a threshold and return one or the other color. This has to be done in a way that I can bind to in an Angular2 Template. How should I do this?

Update:



Here is the html:

<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [colors]="colors" [options]="barChartOptions" [legend]="barChartLegend"
[chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
</canvas>

Answer

In your html:

...[colors]="getColors()"

In your .ts file:

getColors() {
  return [{
     backgroundColor: this.barChartData.map(d => d > threshold ? red : green)
   }];
}
Comments