Angular and D3.js – tutorial


Goal: use the D3.js library in an Angular project.

Here the steps to integrate the library with Angular.

In the package.json we have to declare the dependencies with d3:

    "@types/d3": "^4.4.1", 
    "@types/d3-scale": "^1.0.6", 
    "d3": "^4.5.0", 
    "d3-scale": "^1.0.4", 

In vendor.ts:

    // d3.js 
    import 'd3/build/d3.min'; 
    import 'd3-scale/build/d3-scale.min'; 

In the component that will generate the view you have to import the d3 types:

    import * as d3 from "d3"; 
    import * as d3scale from "d3-scale"; 

In the component we declare the style used and we reference the external xml

    @Component({ 
        selector: 'd3-example', 
        templateUrl:'../html/d3.html', 
        providers: [ConstantsService, Location], 
        styles:[`.chart div { 
        font: 10px sans-serif; 
        background-color: steelblue; 
        text-align: right; 
        padding: 3px; 
        margin: 1px; 
        color: white; 
        }`], 
        encapsulation: ViewEncapsulation 
            .None 
        }) 

The external html simply declare the object that will be modified by the library (chart):

    <h3>Example with D3</h3> 
    <div class="chart"></div> 

Your class has to implement AfterViewInit. This method is called after that Angular initialises the component's view and child views.

export class D3Component implements OnInit, AfterViewInit

    ngAfterViewInit() { 
        var data = [10, 20 ,30 ,15, 4, 26, 33]; 
        d3.select(".chart") 
            .selectAll("div") 
            .data(data) 
            .enter().append("div") 
            .style("width", function(d) { return d*10 + "px"; }) 
            .text(function(d) { return d; }); 
    }