在我的有角项目中,我试图为仪表板绘制一些图表。我正在使用chart.js绘制角度为7的图表。问题是,我不知道应该绘制多少个图表,并且数量将基于http服务调用来确定。该http调用将放置到数据库表中。图表还将是来自实时数据的实时图表。我正在使用以下逻辑绘制图表
<div [hidden]="!charts" class="divchart">
<canvas *ngFor="let chart of charts; let i = index" id="canvas{{i}}" >{{chart}}</canvas>
</div>
但是这不适用于服务返回的数据。为此,我还准备了stackblitz。
请提出处理建议。
非常感谢。
我认为此答案有助于创建多个动态图表。
父母:
HTML:
<div [hidden]="!charts" class="divchart">
<div *ngFor="let chart of charts; let i = index">
<app-child [chart]="chart" [id]="i"></app-child>
</div>
</div>
TS:
import { Component } from '@angular/core';
import { ListService } from './list.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public charts = [];
constructor(private listsrv: ListService) { }
ngOnInit() {
this.charts.push('canvas0');
this.listsrv.getPosts()
.subscribe(
result => {
for(var key in result){
if(result[key].id < 3){
this.charts.push('canvas'+ result[key].id);
}
}
},
error => {console.log(' error',error)},
() => {
console.log('service call completed',this.charts)
}
)
}
}
子:
HTML:
<div *ngIf="chart">
<canvas id="{{chart}}" width="400" height="400">{{chart}}</canvas>
</div>
TS:
import { Component, OnInit, Input } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() chart: any;
@Input() id: any;
constructor() { }
ngOnInit() {
}
ngAfterViewInit() {
this.addchart(this.chart);
}
addchart(chartid){
console.log(chartid);
console.log(document.getElementById(chartid));
var canvas = <HTMLCanvasElement> document.getElementById(chartid);
var ctx = canvas.getContext("2d");
var mychart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Cyan'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3, 7],
backgroundColor: 'lightgreen',
borderColor: 'blue',
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
您也可以通过提供的链接进行检入:https://stackblitz.com/edit/angular-dinauz