Reputation: 1304
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
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>
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">
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">
Upvotes: 1
Reputation: 4792
You have to check data variable length like
<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>
export class AppComponent {
public lineChartData: ChartDataSets[] = [
{ data: [], label: 'Series A' },
];
}
Upvotes: 1