Angular chart.js TypeError:项为空

Angular chart.js TypeError:项为空,angular,typescript,chart.js,Angular,Typescript,Chart.js,我正在编写一个应用程序,它将数据从服务器拉入包装器组件,格式化数据,并将其传递给多个图表组件。但是,当我去创建图表对象时,我得到一个错误:TypeError:item为null 这是我的密码: dashboard.component.html <h1>A</h1> <app-chart *ngIf="dataLoaded | async" [type]="'charta'" [data]="{labels: this.data.labels, readings: t

我正在编写一个应用程序,它将数据从服务器拉入包装器组件,格式化数据,并将其传递给多个图表组件。但是,当我去创建图表对象时,我得到一个错误:
TypeError:item为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>
<div style="display: block;">
<canvas [attr.id]="type" width="400" height="400" >{{ chart }}</canvas>
</div>
<div style="display: block;">
<canvas #myChart width="400" height="400" ></canvas>
</div>

有什么想法吗?

您可以尝试改用ViewChild

试试这个

chart.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>
<div style="display: block;">
<canvas [attr.id]="type" width="400" height="400" >{{ chart }}</canvas>
</div>
<div style="display: block;">
<canvas #myChart width="400" height="400" ></canvas>
</div>

可能太晚了,但在类似的问题上,对我有效的是事情的顺序

按照
Chart.js
上的示例,我将图表部分放在
test.js
中,我在
body
标记的开头调用了该部分。然后是
画布
。该错误是由于
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>

最后,我通过将
this.type
作为字符串传递给
new Chart()
,然后在
ngAfterViewInit()中调用函数来修复它。
wow。.你是对的。.事情的顺序是,我使用的是vuejs,我必须在装载时而不是在创建时初始化。.谢谢