我正在構建一個 Angular 應用程式,我想通過回圈遍歷以下陣列來顯示使用Chart.js的圖表串列:
data = [
{
id: 'chartOne',
title: 'Chart One',
type: 'bar',
lables: ['Villas By Taru', 'Watch Tower'],
data: [18, 12],
},
{
id: 'chartTwo',
title: 'Chart Two',
type: 'bar',
lables: ['Tea Avenue', 'The Grill Bar'],
data: [18, 12, 2, 7],
},
];
- 我正在使用
*ngFor在視圖上呈現圖表串列。 - 我正在遍歷上述陣列以創建一個
new Chart物件并配置圖表。
HTML
<div *ngFor="let data of data">
<canvas [id]="data.id"></canvas>
</div>
TS
import { Component, OnInit, VERSION } from '@angular/core';
import { Chart, registerables } from 'chart.js';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
data = [
{
id: 'chartOne',
title: 'Chart One',
type: 'bar',
lables: ['Villas By Taru', 'Watch Tower'],
data: [18, 12],
},
{
id: 'chartTwo',
title: 'Chart Two',
type: 'bar',
lables: ['Tea Avenue', 'The Grill Bar'],
data: [18, 12, 2, 7],
},
];
ngOnInit() {
this.data.forEach((element) => {
this.generateType(element);
});
}
generateType(data: any) {
const myChart = new Chart(data.id, {
type: 'bar',
data: {
labels: data.labels,
datasets: [
{
label: '# of Votes',
data: data.data,
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: {
y: {
beginAtZero: true,
},
},
},
});
}
}
這種方法不起作用并引發以下錯誤:
chart.esm.js:5343 Failed to create chart: can't acquire context from the given item
你可以在這里找到代碼庫:StackBlizEditorURL
我在這里做錯了什么?請幫幫我。
uj5u.com熱心網友回復:
我認為您使用錯誤的生命周期掛鉤來創建圖表。
在ngOnInit 中,組件視圖尚未初始化。因此 DOM 中沒有 DOM 元素,data.idChart.js 會拋出錯誤。
要使用的正確生命周期鉤子是ngAfterViewInit。
所以你必須更換
ngOnInit() {
this.data.forEach((element) => {
this.generateType(element);
});
}
和
ngAfterViewInit() {
this.data.forEach((element) => {
this.generateType(element);
});
}
并相應地更新匯入。
您可以在此處閱讀有關 Angulars 生命周期掛鉤的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352699.html
