How to make a basic line chart Directive in Angular 8 with D3 ?




Angular is so complex. A lot of different with vanilla Javascript. So, this tutorial with exploring deeper and deeper how to make angular 8 and d3 become a perfect match.



Before we get started, let's create a new StackBlitz workspace.
StackBlitz will setup all files you need about developing angular, so it's very convenient.
In this tutorial, all files you can find in the link down below.

Source Code : https://stackblitz.com/edit/tutorial1-data-visualization-with-angular-8-d3js


1.
Import 2 libraries - "@type/d3" and "d3"



2.
Create a new folder - "directive"
Inside we create 2 .ts files - "line-chart.directive.ts" & "line-chart.directives.spec.ts"



3.
Open "app.module",  make our directive import in angular.



4.
And now, we're going to create something about d3.
Open "line-chart.directive.ts" and import d3.



5.
Next, import "ElementRef", it will let us select DOM like vanilla JS.



6.
Create a function - "createLineChart()"
We'll put d3 line-chart code here. 
Meanwhile, call the function in the constructor.



7.
Almost done!
Open "app.component.html", and adding you directive to any tag you prefer. I just add a new div and put it there.



8.
There you go! Your line-chart is already created!



This tutorial is focus on connecting Angular an D3.

If you have any question, joining our group and discussing with others!

Post a Comment

較新的 較舊