Chris
Chris

Reputation: 1304

Custom empty screen for ng2-charts

I am working on Line Chart in ng2-charts. I am trying to show chart if there is data and if not, I want to show No Data Available instead of empty chart.

HTML

<div style="display: block;" *ngIf="lineChartData">
  <canvas  baseChart width="400" height="400"
    [datasets]="lineChartData"
    [labels]="lineChartLabels"
    [options]="lineChartOptions"
    [colors]="lineChartColors"
    [legend]="lineChartLegend"
    [chartType]="lineChartType"
    [plugins]="lineChartPlugins">
  </canvas>
</div>

TS

public lineChartData: ChartDataSets[] = [
    { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
];
public lineChartLabels: Label[] = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

Checkout Stackblitz

Upvotes: 1

Views: 1783

Answers (2)

acdcjunior
acdcjunior

Reputation: 135812

You could use *ngIf's else block:

<div style="display: block;" *ngIf="lineChartData; else elseBlock">
  <canvas baseChart width="400" height="400"
    [datasets]="lineChartData"
    [labels]="lineChartLabels"
    [options]="lineChartOptions"
    [colors]="lineChartColors"
    [legend]="lineChartLegend"
    [chartType]="lineChartType"
    [plugins]="lineChartPlugins">
  </canvas>
</div>
<ng-template #elseBlock>No Data Available.</ng-template>

Stackbliz demo here.

If lineChartData can be just empty ([]) and you wish to also hide the chart in this case, you can use:

<div style="display: block;" *ngIf="lineChartData && lineChartData.length; else elseBlock">

Stackblitz demo 2 here.

And/or if you want to guard the data variable as well, do:

<div style="display: block;" *ngIf="lineChartData && lineChartData.length && lineChartData[0].data.length; else elseBlock">

Demo here.

Upvotes: 1

Paresh Gami
Paresh Gami

Reputation: 4792

You have to check data variable length like

html

<div style="display: block;" *ngIf="lineChartData[0]['data'].length">
  <canvas baseChart width="400" height="400"
    [datasets]="lineChartData"
    [labels]="lineChartLabels"
    [options]="lineChartOptions"
    [colors]="lineChartColors"
    [legend]="lineChartLegend"
    [chartType]="lineChartType"
    [plugins]="lineChartPlugins">
  </canvas>
</div>

<div *ngIf="lineChartData[0]['data'].length === 0 ">
  No Data Available
</div>

ts

export class AppComponent  {
  public lineChartData: ChartDataSets[] = [
    { data: [], label: 'Series A' },
  ];
}

Upvotes: 1

Related Questions