C3.js is a high-level API on top of D3.js. It has an active community for support, is highly customizable, and benefits from having great code reusability. It has a steep learning curve and is more limited when it comes to the number of charts offered.
Angular is a popular open-source framework developed by Google for building dynamic web applications. It's part of a broader ecosystem that includes tools and libraries designed to work together to enable efficient development of high-quality applications. Angular is known for its robustness, scalability, and ability to create single-page applications (SPAs) that offer a smooth, native-like user experience. Angular has a component-based architecture, enabling great modularity. Additionally, it is great at syncing data between a view and a model. It can have a steep learning curve, but has a great community and high performance.
In this example, we'll demonstrate how to integrate the C3.js chart library with Angular to create dynamic and responsive charts. We will create a simple line chart component using C3.js.
First, ensure that you have Angular CLI installed. If not, you can install it using npm:
npm install -g @angular/cli
Next, create a new Angular project:
ng new angular-c3-example
Navigate into your project directory:
cd angular-c3-example
C3.js is built on top of D3.js, so we need to install both libraries:
npm install c3 d3
Add the C3.js stylesheet link to the angular.json
file under the styles
array:
"styles": [
"src/styles.css",
"./node_modules/c3/c3.min.css"
],
Generate a new component for the chart:
ng generate component line-chart
In the line-chart.component.ts
file, import C3 and D3 and implement the chart:
import { Component, OnInit } from '@angular/core';
import * as c3 from 'c3';
import * as d3 from 'd3';
@Component({
selector: 'app-line-chart',
templateUrl: './line-chart.component.html',
styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {
constructor() { }
ngOnInit() {
this.generateChart();
}
generateChart() {
const chart = c3.generate({
bindto: '#chart',
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
}
});
}
}
Then, add a div element for the chart in the line-chart.component.html
file:
<div id="chart"></div>
Finally, add the line chart component to your app component template (app.component.html
):
<app-line-chart></app-line-chart>
This will display the line chart when you run your Angular application.
Start the development server with Angular CLI:
ng serve
Open your browser and navigate to http://localhost:4200/ to see the chart.
With these steps, you've successfully integrated C3.js charts into your Angular application. You can customize the chart data and options as needed for your project.