ng2-charts的自定义空白屏幕

时间:2019-05-09 05:08:08

标签: angular chart.js ng2-charts

我正在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'];

结帐Stackblitz

2 个答案:

答案 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>

Stackbliz demo here

如果lineChartData可以为空([]),并且您希望在这种情况下也隐藏图表,则可以使用:

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

Stackblitz demo 2 here.

并且/或者,如果您也想保护data变量,请执行以下操作:

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

Demo here.

答案 1 :(得分:1)

您必须检查数据可变长度,如

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' },
  ];
}