a blog for those who code

Friday, 11 June 2021

Interactive D3.js Pie Chart using DropDown Selector in Angular

In this tutorial, we will see how to build an interactive D3.js Pie Chart with a dropdown selector. I have gone through the code at D3 Graph Gallery where they were using two buttons to update the data. 

In my case, I was using Angular 8 and the data in the dropdown is dynamic. So to do the change I have created a Pie Chart component that takes pie data and displays the pie chart accordingly. The list and data are dynamic and thus on change of the dropdown list, I have to change the data accordingly.

A Simple Pie Chart Component will be called in my HTML using the below code, where pieData is the data we are sending to the child component.

<app-d3-pie [isPercentage]="true" [pieData]="data"></app-d3-pie>

Along with that, I have also added the below code, where the dropdown list is created dynamically and on selection change we are calling the function with the updated value to change the data accordingly.


  <label id="lbl">Servers:</label>

  <select id="itemList" #siteServer [(ngModel)]="itemKey" (change)="itemChange(siteServer.value)">

    <option *ngFor="let site of itemList" [id]="site" [value]="site">{{site}}</option>



Now in my TypeScript file, the item change function code is, where on change of item we are selecting the appropriate data. For the sake of the tutorial, I have created two dummy list and thus I am populating the list on a change of item. But this will be dynamic in the real application.

itemChange(value: string) {


  this.itemKey = value;

  this.data = value === 'Item 1'

        ? JSON.parse(JSON.stringify(this.data1))

        : JSON.parse(JSON.stringify(this.data2));


You can check the whole code in StackBlitz. I have taken the initial code from another StackBlitz.

No comments:

Post a Comment