0% found this document useful (0 votes)
131 views5 pages

Chart Js Pie Angular - Google Docs

This document discusses how to create a pie chart using Chart.js and Angular. It includes instructions on installing necessary modules, importing the ChartsModule, creating a Chart model, adding chart code to the component template and class, making a service call to retrieve chart data, and setting up an API to return mock data. The component initializes the chart options, labels, and data and passes it to the template to display the pie chart.

Uploaded by

Leader Leader
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views5 pages

Chart Js Pie Angular - Google Docs

This document discusses how to create a pie chart using Chart.js and Angular. It includes instructions on installing necessary modules, importing the ChartsModule, creating a Chart model, adding chart code to the component template and class, making a service call to retrieve chart data, and setting up an API to return mock data. The component initializes the chart options, labels, and data and passes it to the template to display the pie chart.

Uploaded by

Leader Leader
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

chart Js pie Angular

1 : install modules
npm i [email protected]
npm i [email protected]
npm i [email protected]
2 : app .module.ts
import { ChartsModule } from 'ng2-charts';
imports: [
ChartsModule
]

mkdir model
cree fichier chart.ts
export class Chart {
teamOne: string;
teamTwo: string;
scoreOne: number;
scoreTwo: number;
}

example :
3 :chart.html
<div class="top-charts">
<div class="chart">
<canvas baseChart [data]="pieChartData"
[labels]="pieChartLabels" [chartType]="pieChartType"
[options]="pieChartOptions" [plugins]="pieChartPlugins"
[colors]="pieChartColors" [legend]="pieChartLegend">
</canvas>
</div>
</div>

4:chart.ts
import { Component, OnInit } from '@angular/core';
import { ChartType, ChartOptions } from 'chart.js';
import { Label } from 'ng2-charts';
import * as pluginDataLabels from 'chartjs-plugin-datalabels';
import { MatchService } from 'src/app/service/match.service';
import { Chart } from '../../models/Chart';

@Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: [ './chart.component.css' ]
})
export class ChartComponent implements OnInit {

chartData: Chart[] = [];

public pieChartOptions: ChartOptions = {


responsive: true,
legend: {
position: 'top'
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
const label = ctx.chart.data.labels[ctx.dataIndex];
return label;
}
}
}
};
public pieChartLabels: Label[] = [];
public pieChartData: number[] = [];
public pieChartType: ChartType = 'pie';
public pieChartLegend = true;
public pieChartPlugins = [ pluginDataLabels ];
public pieChartColors = [];
constructor(private api: MatchService) {}

ngOnInit() {
this.getChartData();

}
getChartData() {
this.api.getChart().subscribe(
(res: any) => {
console.log('here res chart', res);
this.chartData = res.matches;
this.pieChartLabels = [];
this.pieChartData = [];
this.pieChartColors = [];
const backgrounds = [];
this.chartData.forEach((ch, idx) => {
this.pieChartLabels.push(ch.teamOne);
this.pieChartData.push(ch.scoreOne);
backgrounds.push(`rgba(${0 + idx * 10}, ${255 - idx
* 20}, ${0 + idx * 10}, 0.3)`);
});

console.log('final array', this.pieChartLabels);


console.log('final array', this.pieChartData);

this.pieChartColors = [
{
backgroundColor: backgrounds
}
];
},
(err) => {
console.log(err);
}
);
}
}

5 : Service.ts :
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { Chart } from './../models/Chart';

@Injectable({
providedIn: 'root'
})
export class MatchService {
matchUrl = 'http://localhost:3000/matches';
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
};
}
constructor(private httpClient: HttpClient) {}

getChart(): Observable<Chart> {
const url = `${this.matchUrl}`;
return this.httpClient
.get<Chart>(url)
.pipe(tap((_) => console.log(`fetched chart data`)),
catchError(this.handleError<Chart>(`getChart data`)));
}
}

6 : app.js
// traitement logique de matches
app.get('/matches', (req, res) => {
console.log('here in get all matches');
Match.find((err, docs) => {
if (err) {
console.log('error widh DB');
} else {
res.status(200).json({
matches: docs
});
}
});
});

You might also like