In this article, I’ll explain several problems that I used to find every time I had to do something with a visual component in Angular and D3.

Just to enlighten you, I’ll use a line chart graph based on this example:

The Problem

There are so many ways to initialise a chart in D3 with Angular, so it can be a problem. Surely, if you did more than three D3 visual components in Angular, you’ve done them in a different way each time.

Let me explain a good way to adjust your charts.

But for the very first step, I’m going to present the instructions to create a new project with Angular and D3.

Creating the Angular project

Use the Angular CLI to quickly set one up:

$ npm install -g @angular/cli

Then start a new project:

$ ng new ng-d3-css-example
$ cd ng-d3-css-example

Integrating D3

Its typings in TypeScript:

$ npm install d3 --save
$ npm install @types/d3 --save-dev

Generate the component

Let’s create a component.

$ ng generate component line-chart

Template

The point here is that for every visual component in D3, I use this code. I love it because it’s only one tag with svg, a class, and an identifier to retrieve it later. That’s it!

<svg #chart class="chart"></svg>

Style

The focus here is the .chart class — it allows us to adjust our chart via CSS. It completely separates how we’re sizing charts from other parts, and it’s done only through the style.

line-chart.component.scss

...

.chart {
    width: 240px;
    height: 230px;

    ...

#typescript #d3js #angular #css #javascript

Responsive Charts in Angular with D3.js and CSS
16.95 GEEK