我正在创建一个跟踪家庭预算的应用程序。我需要向用户显示每个月的收入和支出以及支出的饼图。我正在模板中的ngFor
中遍历对象数组。
我希望能够为每个所谓的“月”显示饼图,其中每个budget
为budget[]
,但只能看到第一个饼图。
这里是https://stackblitz.com/github/avaliaho/budgettracker的Stackblitz,下面是相关的代码段:
monthlybudget.component.html:
<div class="row">
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
<div *ngFor="let budget of budgets">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ budget.date | date }}</h5>
<canvas id="myChart" style="margin-bottom: 12px;" width="800" height="250px" #mychart></canvas>
<table class="table table-responsive">
<thead>
<tr>
<th>Food</th>
<th>Drinks</th>
<th>Housing</th>
<th>Bills</th>
<th>Loans</th>
<th>Travel</th>
<th>Clothing</th>
<th>Insuraces</th>
<th>Hobby</th>
<th>Other</th>
<th>Income</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ budget.food }}€</td>
<td>{{ budget.drinks }}€</td>
<td>{{ budget.housing }}€</td>
<td>{{ budget.bills }}€</td>
<td>{{ budget.loans }}€</td>
<td>{{ budget.travel }}€</td>
<td>{{ budget.clothing }}€</td>
<td>{{ budget.insurances }}€</td>
<td>{{ budget.hobby }}€</td>
<td>{{ budget.other }}€</td>
<td>{{ budget.income }}€</td>
</tr>
</tbody>
</table>
</div>
</div>
<br>
</div>
</main>
</div>
monthlybudget.component.ts:
import { Component, OnInit, ViewChild } from '@angular/core';
import { BudgetService } from '../budget.service';
import { budget } from '../budget.interface';
import { Chart } from 'chart.js';
@Component({
selector: 'app-monthlybudget',
templateUrl: './monthlybudget.component.html',
styleUrls: ['./monthlybudget.component.css']
})
export class MonthlybudgetComponent {
budgets: budget[] = [];
canvas: any;
ctx: any;
@ViewChild('mychart') mychart;
constructor(private service: BudgetService) {}
ngOnInit() {
this.budgets = this.service.getAll();
}
ngAfterViewInit() {
this.canvas = this.mychart.nativeElement;
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
datasets: [{
label: 'Expenses',
backgroundColor: "rgba(0, 123, 255,0.4)",
borderColor: "rgb(0, 123, 255)",
fill: true,
data: [
this.budgets[0].drinks,
this.budgets[0].food,
this.budgets[0].hobby,
this.budgets[0].housing,
this.budgets[0].insurances,
this.budgets[0].loans,
this.budgets[0].netflix,
this.budgets[0].other
],
}],
labels: ['Drinks', 'Food', 'Hobby', 'Housing', 'Insurance', 'Loans', 'Netflix', 'Other']
},
options: {
responsive: true,
title: {
display: true,
text: 'Expenses'
}
}
});
}
}