javascript - 在 Angular 10 中使用 chart.js 创建多个动态堆叠图表?
问题描述
我正在尝试以角度创建多个图表,但我不确定我尝试实现 will 的方式是否正确,并且我无法创建多个图表并将其替换为另一个
<div *ngIf="chartData.length !== 0">
<app-limus-utilisation-chart
*ngFor="let entity of chartData" [chartdata]="entity"
></app-limus-utilisation-chart>
</div>
图表组件.ts
getStackedChart() {
const canvas: any = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
var data = {
labels: this.chartdata.buyernames,
datasets: [{
label: 'Utilised Limit',
data: this.chartdata.utilisedlimitData,
backgroundColor: '#22aa99'
}, {
label: 'Available Limit',
data: this.chartdata.availablelimit,
backgroundColor: '#994499'
}]
}
chartJsLoaded$.pipe(take(1)).subscribe(() => {
setTimeout(() => {
this.myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
mode: 'index',
intersect: true,
position: 'custom',
yAlign: 'bottom'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: false,
display: false
}]
}
}
});
})
})
}
我尝试了两种方法
使用 view child 未创建图表,创建了 getElementById 图表,但第二个图表替换了第一个图表。但我想要两个并排的堆叠图表如何实现这一点
并且当前图表采用低于 100 的值,但根据我的实际要求,我需要显示类似 (1000000, 700000) 的提示金额,也就是货币格式
像这样我试图实现 https://stackblitz.com/edit/angular-chart-js-j26qhm?file=src%2Fapp%2Fapp.component.html
请给建议
得到答案后,我取得了一些成就
解决方案
问题是这里的这一行:
const canvas: any = document.getElementById('canvas1');
您在页面上有多个具有该 ID 的元素(因为您执行了 *ngFor),因此它始终将自身附加到页面上的第一个元素。
与其使用 getElementByID,不如使用 Angular 的内置@ViewChild
.
像这样:
chart.component.html:
<canvas #stackchartcanvas></canvas>
chart.component.ts:
@ViewChild("stackchartcanvas") myCanvas: ElementRef<HTMLCanvasElement>;
....
....
....
getStackedChart() {
const canvas = this.myCanvas.nativeElement;
}
Stackblitz:https ://stackblitz.com/edit/angular-chart-js-kny4en?file=src%2Fapp%2Fchart.component.ts
(此外,在您的原始代码中,this.chartData.push()
每次单击复选框时都会运行,即使复选框为假,但这是一个不同的、不相关的问题,该问题也已得到修复。)
推荐阅读
- intellij-idea - 如何在 IntelliJ IDEA 中禁用双引号自动转义?
- arrays - 如何使用具有多个子类别的表视图控制器
- java - 使用 '|' 将字符串拆分为子字符串 特点
- python-3.x - 在 Python3.x 中使用 argparse 时如何为可选参数添加必需的值
- c# - 由于多次实例化,EventHandler null
- sql - 如何将日期和时间拼接成时间戳?
- javascript - 搜索打开的转义方括号在“javascript 搜索功能”中的行为与标准正则表达式不同
- python - 使用分隔符将文本发送到带有熊猫的不同列
- python - 使用 GUI 从 Arduino 控制串行数据传输
- python - 在熊猫中计算具有UTM坐标的数据框的距离