Integrating D3js with Angular 5.0

D3js is very popular and powerful JavaScript framework to build Data Driven web application.

Angular is a framework to build SPA with Typescript and getting popular day by day. Though there is tough fight with React.js and Angular, I like Angular most.

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

Steps:

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”;

  1. 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() {
d3.select(“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.

Solution:

Pass $event argument to click event handler on <svg> tag

<svg width=”100%” height=”1200" class=”mySvg” (click)=”clicked($event)”>

Click event handler inside .ts

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.

You can play around website here:

Source code can be found here:

https://github.com/ultrasonicsoft/d3-ng5-demo

Cheers!

Cloud Solution Architect | Author | Full Stack Developer | https://www.linkedin.com/in/balram-chavan | https://www.hiretheauthor.com/balramchavan

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store