Currently, I am in the process of developing a macronutrient calculator as part of a project. The idea is to have a form where users can input values, and a corresponding doughnut chart will display with initial values set at 0
. However, upon clicking the submit button, the chart fails to update.
Below is the code snippet:
home.component.html
<form (submit)="addMeal(totalGrams, proteinGrams, fatGrams, carbGrams)">
<div class="form-group">
<input
class="form-control"
type="number"
placeholder="Total"
#totalGrams
/>
</div>
<div class="form-group">
<input
class="form-control"
type="number"
placeholder="Protein"
#proteinGrams
/>
</div>
<div class="form-group">
<input
class="form-control"
type="number"
placeholder="Fat"
#fatGrams
/>
</div>
<div class="form-group">
<input
class="form-control"
type="number"
placeholder="Carbs"
#carbGrams
/>
</div>
<button type="submit" class="btn btn-primary btn-block">
Submit
</button>
</form>
The provided code snippet focuses on the form structure only, excluding irrelevant layout details and Bootstrap components.
home.component.ts
import { Component, ViewChild } from '@angular/core';
import { ChartData, ChartType } from 'chart.js';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
gProtein: number = 0;
gCarbs: number = 0;
gFat: number = 0;
public doughnutChartLabels: string[] = [ 'Protein', 'Carbohydrates', 'Fat' ];
public doughnutChartData: ChartData<'doughnut'> = {
labels: this.doughnutChartLabels,
datasets: [
{ data: [ this.gProtein, this.gCarbs, this.gFat ] },
]
};
public doughnutChartType: ChartType = 'doughnut';
addMeal(totalGrams: HTMLInputElement, proteinGrams: HTMLInputElement, fatGrams: HTMLInputElement, carbGrams: HTMLInputElement) {
this.doughnutChartData.datasets[0].data[0] = parseInt(proteinGrams.value);
this.doughnutChartData.datasets[0].data[1] = parseInt(carbGrams.value);
this.doughnutChartData.datasets[0].data[2] = parseInt(fatGrams.value);
totalGrams.value = ''
proteinGrams.value = ''
fatGrams.value = ''
carbGrams.value = ''
totalGrams.focus()
return false;
}
}
Although unsure of the last update for this library, following the documentation guide is important for updating the chart effectively, especially if certain sections lack clarity.