Я создаю приложение, которое отслеживает бюджет домашнего хозяйства. Мне нужно отобразить доход и расходы за каждый месяц для пользователя вместе с круговой диаграммой расходов. Я перебираю массив объектов с ngFor
в шаблоне.
Я ожидаю, что смогу отобразить круговую диаграмму для каждого из так называемых «месяцев», отдельного budget
из budget[]
, но вместо этого будет виден только первый круговой символ.
Stackblitz здесь: https://stackblitz.com/github/avaliaho/budgettracker и вот соответствующие фрагменты кода:
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'
}
}
});
}
}