It is very easy to integrate D3js with Angular and start building SPA with power of D3js.


Create new Angular project using angular/cli

ng new d3-ng5-demo

Once new project is created and dependencies are installed, install D3js

 npm install d3

Import D3 and start using it inside your components. For example, import “d3” in app.component.ts file as below:

import * as d3 from “d3”;

Select your HTML element using d3js for data join operation/DOM operation. ngAfterContentInit() life cycle hook is best place to select element using D3 since by this time, DOM is ready for current component.

ngAfterContentInit() {“p”).style(“color”, “red”);

If you have <p> tag inside app.component.html file, once browser is done loading app.component, <p> tag shall have color red.

Resolving “this” scope

In Angular, inside .ts file “this” object is used to refer member variable(s) and member function(s). Whereas in D3js, “this” object is filled with selected HTML element.

Consider a scenario, we want to draw circle on mouse click position on app.component.html. We shall keep “radius” of circle as a member variable of AppComponent class.


Pass $event argument to click event handler on tag

<svg width=”100%” height=”1200" class=”mySvg” (click)=”clicked($event)”> Click event handler inside.ts:

clicked(event: any){
attr('cx' , event.x).
attr('cy' , event.y).
attr('r' , this.radius).
attr('fill' , 'red')

That’s it! In browser, if you click anywhere in <svg> tag; you shall see red circle being plotted at mouse position with radius 10.

Related Query