How to create reusable chart components with Angular 4 & NvD3 [Code Included]4 min read

How about generating interactive dynamic charts using angular 4 from JSON Object? D3.js a JavaScript library that manipulates documents based on data, exactly helps this possible. By binding arbitrary data to a Document Object Model (DOM).

D3 complies with the web standards giving you the full capability of modern browsers so that you could create interactive SVG charts with smooth transitions and better interaction. It effectively uses the power of visualization components and a data-driven approach to make this possible.

D3 Charts with Angular 4

Angular 4 reusable charts

D3 is also extremely fast, have support for large datasets, and also offers dynamic behaviours for better interaction and animation.

Integrate D3.js with the Angular 4 component life cycle to create reusable charts and other visualizations that support animation and dynamic data. Okay, now let us walk through the steps to create an interactive chart (that can be reused across) like the one shown here!

Step1: Firstly, we need to Add Package dependencies in your package.json file.

"dependencies": 
{
"d3": "^3.5.5",
"ng2-nvd3": "^1.1.3",
"nvd3": "^1.8.4"
},
"devDependencies": 
{
"typings": "^1.0.4",
"@types/d3": "^0.0.33",
"@types/nvd3": "^1.8.32",
}

Step2: Right click on your package.json file and select Restore Package option.

Step3: After completing the package installations, need to Add this line in your

systemjs.config.js file.
map: {

'app': 'app',
// Include this libraries
'ng2-nvd3': './node_modules/ng2-nvd3/build/lib/ng2-nvd3.js',

'nvd3': './node_modules/nvd3/build/nv.d3.min.js',

'd3': './node_modules/d3/d3.min.js'

}
And include this dependency files in your main Index.html File:
<script src="/node_modules/d3/d3.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="/node_modules/nvd3/build/nv.d3.min.css" />
<script src="/node_modules/nvd3/build/nv.d3.min.js"></script>

Step4: Add this line in your tsconfig.json file.

"noImplicitAny": false,

Step5: Import necessary packages  in your app.module.js file.

import { nvD3 } from 'ng2-nvd3';
 
import 'd3';
import 'nvd3';
 
@NgModule({
declarations: [nvD3,AppComponent], // Components goes here
})

Step6: Add this line in your Chart component  files then add your chart code.

ViewEncapsulation to be included in your code.
import { Component, OnInit, ViewEncapsulation, ElementRef, ViewChild, AfterViewInit  } from '@angular/core';
 
import * as D3 from "d3";
declare let d3: any;
 
@Component({
encapsulation: ViewEncapsulation.None,
})

Step7:  Sample Chart Data and Implementation functions code:

Sample Api Response Data: (this.serviceResponseData) 
 
{
"Labels": ["One","Two","Three"],
"Data": [12,20,30],
"BGColour": ["#000000","#FF0000","#FFFF00"],
"TotlaCount": "2000"
}
 
//Response Data Convert to Chart Object
createRange(serviceResponseData) {
var items: number[] = [];
var pushObject: any = {};
 
for (var i = 0; i < serviceResponseData.Data.length; i++) {
pushObject = {
key: serviceResponseData.Labels[i],
y: serviceResponseData.Data[i],
color: serviceResponseData.BGColour[i],
totalCount: serviceResponseData.TotlaCount
};
 
items.push(pushObject);
}
return items;
}
 

Step8:  Draw chart functions code:
 

// Make Donut Chart Data
makeDonutChart() {
 
this.options = {
chart: {
type: 'pieChart',
height: 270,
donut: true,
x: function (d) { return d.key; },
y: function (d) { return d.y; },
showLabels: false,
showLegend: false,
duration: 500,
labelThreshold: 0.01,
labelSunbeamLayout: true,
donutRatio: 0.7,
color: function (d, i) {
return (d.color);
},

legend: {
margin: {
top: 5,
right: 35,
bottom: 5,
left: 0
}
},
tooltip: {
contentGenerator: function (e) {
var series = e.series[0];
if (series.value === null) return;
 
var header =
"<thead>" +
"<tr>" +
"<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" +

"<td class='key'><strong>" + series.key + "</strong> : </td>" +
"<td class='x-value'><strong>" + series.value + "</strong></td>" +

"</tr>" +
"</thead>";
 
return "<table>" +
header +
"</table>";
}
},

callback: function () {
var svg = d3.select("#DonutChart svg");
var donut = svg.selectAll("g.nv-pie").filter(
function (d, i) {
return i == 1;
});
 
donut.insert("text", "g")
.text(function (d, i) {
debugger;
return d[i].totalCount;
})
.attr("class", "css-label-class")
.attr("text-anchor", "middle")
.attr('dy', '0.35em');
},
pie: {
dispatch: {
elementMouseover: function (e) {
 
var svg = d3.select("#DonutChart svg");
var donut = svg.selectAll("g.nv-pie").filter(
function (d, i) {
return i == 1;
});

 
donut.insert("text", "g")
.text(function (d, i) {
return d[i].totalCount;
})

.attr("class", "css-label-class")
.attr("text-anchor", "middle")
.attr('dy', '0.35em');
 
},

elementMouseout: function (e) { }
}
}
}
};

 
this.data = this.createRange(this.pushChartObject);
}

 
 
Step9:  Use the below code for Chart Binding in Html View
 

<nvd3 [options]="options" [data]="data" id="DonutChart"></nvd3>

Congratulations, if you were able to make it up following these steps. If you are stuck up somewhere, don’t worry yet. I am available at the comments section below for your rescue. You could also post a link to your chart and share that with our community here.

About the author

Santhosh Kumar

Leave a Reply

Your email address will not be published. Required fields are marked *