Angular Application using ngx-charts
Ngx-charts is an open-source angular library that can be used for data visualizations of quantitative information in the form of charts, graphs, plots, etc.,
Let's try to understand how we can install and use it within an angular application.
Install Library
Run the below command on the terminal to install the library.
> npm install @swimlane/ngx-charts --save
If we need to use any specific shapes, then we need to install the De dependencies as shown below. However, they are not required for this tutorial.
> npm install d3 --save npm install @types/d3-shape --save
Import Library
Include NgxChartsModule
as one of the imports in the module. In our case, we have only one module, so include it in the app.module.ts
file.
This includes all the components from the charts module into the module AppModule
so that they are available for all the components of the module.
import { NgxChartsModule } from '@swimlane/ngx-charts';
@NgModule({
imports: [NgxChartsModule],
})
export class AppModule {
}
Use Components
Update the component's typescript file with the properties we need for the chart, as shown below.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor() {
}
data = [
{ name: 'Germany', value: 8940000 },
{ name: 'USA', value: 5000000 },
{ name: 'France', value: 7200000 }
];
view: any[] = [700, 400];
// options
gradient: boolean = true;
showLegend: boolean = true;
showLabels: boolean = true;
isDoughnut: boolean = false;
legendPosition: string = 'below';
colorScheme = {
domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA'],
};
onSelect(data): void {
console.log('Item clicked', JSON.parse(JSON.stringify(data)));
}
onActivate(data): void {
console.log('Activate', JSON.parse(JSON.stringify(data)));
}
onDeactivate(data): void {
console.log('Deactivate', JSON.parse(JSON.stringify(data)));
}
}
Include the below HTML code in the component's HTML file to include the respective chart.
<ngx-charts-pie-chart
[view]="view"
[scheme]="colorScheme"
[results]="single"
[gradient]="gradient"
[legend]="showLegend"
[legendPosition]="legendPosition"
[labels]="showLabels"
[doughnut]="isDoughnut"
(select)="onSelect($event)"
(activate)="onActivate($event)"
(deactivate)="onDeactivate($event)">
</ngx-charts-pie-chart>
How does it look on the application?
The generated pie chart looks like the one below.
Conclusion
Now, we know how to use the ngx-charts
library in an Angular application.