chart.js TypeError:item为null

时间:2018-04-21 08:31:26

标签: angular typescript chart.js

我正在编写一个应用程序,它将数据从服务器提取到包装器组件,格式化数据,并将其传递给多个图表组件。但是,当我去创建图表对象时,我收到错误:TypeError: item is null

这是我的代码:

dashboard.component.html

<h1>A</h1>
<app-chart *ngIf="dataLoaded | async" [type]="'charta'" [data]="{labels: this.data.labels, readings: this.data.charta}"></app-chart>
<h1>B</h1>
<app-chart *ngIf="dataLoaded | async" [type]="'chartb'" [data]="{labels: this.data.labels, readings: this.data.chartb}"></app-chart>

chart.component.html

<div style="display: block;">
<canvas [attr.id]="type" width="400" height="400" >{{ chart }}</canvas>
</div>

chart.component.ts

....
export class ChartComponent implements OnInit {
  @Input() data: any;
  @Input() type: string;

  chart: any;

  createChart() {
    const canvas = this.elementRef.nativeElement.querySelector(`#${this.type}`);
    this.chart = new Chart(canvas, {....});
  }

  ....

  ngAfterContentInit() {
    this.createChart();
  }
}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用ViewChild

试试这个

<强> chart.component.html

<div style="display: block;">
<canvas #myChart width="400" height="400" ></canvas>
</div>

<强> chart.component.ts

export class ChartComponent implements OnInit {
  @Input() data: any;
  @Input() type: string;

  chart: any;

  @ViewChild('myChart')
  myChart: ElementRef;

  createChart() {
    const canvas = this.myChart.nativeElement.getContext("2d");
    this.chart = new Chart(canvas, {....});
  }

  ....

  ngAfterContentInit() {
    this.createChart();
  }
}

答案 1 :(得分:1)

可能为时已晚,但在类似问题上对我有用的是事物的顺序。

按照Chart.js上的示例,将图表部分放在test.js标记的开头的body中。随后是canvas。该错误是由于canvas需要在js调用之前出现。

例如, index.php

<html lang="en">
    <head>
        <title>Charting</title>
    </head>

    <body>
        <script src="node_modules/chart.js/dist/Chart.js"></script>

        <canvas id="myChart" width="400" height="400"></canvas>
        <script src="test.js"></script>
    </body>
</html>

,然后 test.js

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});