我正在Line Chart中研究ng2-charts。我试图显示图表是否有数据,如果没有,我想显示No Data Available
而不是空白图表。
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'];
答案 0 :(得分:1)
您可以使用*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>
如果lineChartData
可以为空([]
),并且您希望在这种情况下也隐藏图表,则可以使用:
<div style="display: block;" *ngIf="lineChartData && lineChartData.length; else elseBlock">
并且/或者,如果您也想保护data
变量,请执行以下操作:
<div style="display: block;" *ngIf="lineChartData && lineChartData.length && lineChartData[0].data.length; else elseBlock">
答案 1 :(得分:1)
您必须检查数据可变长度,如
<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' },
];
}