Create a responsive Angular D3 charts

[fuente: https://school.geekwall.in/p/SJ52XGRWX/create-a-responsive-angular-d3-charts]

While the landscape of frameworks available for structuring and building web applications is changing by the minute, D3 is still the recognized way to create visualizations using Javascript. In this tutorial, we will add a D3 chart to an Angular application and make the size of the graph dynamic.

Note: You can find the finished source code here.

Creating the Angular project

The first step is to create a new Angular project using the CLI, and to add the d3 library to it:

ng new angular-d3
npm install d3 --save
npm install @types/d3 --save-dev

Next, we will create the component that we will work with:

ng generate component bar-chart

Finally, we will replace the content of ‘src/app/app.component.html’ with the following:

<h1>Bar Chart</h1>
<app-bar-chart></app-bar-chart>

Loading and passing data

In this tutorial, we will use this bar chart from Mike Bostock as the D3 visualization. You can find the data in JSON format here, and we will put it in a new asset file at ‘src/assets/data.json’.

We can also create an interface for the data points, in a new file ‘src/app/data/data.model.ts’:

export interface DataModel {
  letter: string;
  frequency: number;
}

To load this data, we can modify the ‘src/app/app.component.ts’ file like this:
angular-d3-app.component.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { DataModel } from 'src/data/data.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data: Observable<DataModel>;

  constructor(private http: HttpClient) {
    this.data = this.http.get<DataModel>('data/data.json');
  }
}

For HttpClient to work, we need to add HttpClientModule to our App NgModule imports in ‘src/app/app.module.ts’.

Finally, we can pass the data to our chart component by modifying ‘src/app/app.component.html’:

<h1>Bar Chart</h1>
<app-bar-chart [data]=”data | async”></app-bar-chart>