Search code examples
angulartypescriptsunburst-diagramangular9

Integrate vasturiano / `sunbrust-chart` with Angular 2-9


It is there a way to integrate vasturiano/sunburst-chart with Angular 2 - 9? I am trying this, but is not working.

import { Component, OnInit } from '@angular/core';
import Sunburst from 'sunburst-chart';
import { sbdata } from '../chart-options/sunburst-mockdata';

@Component({
  selector: 'app-sunburst',
  templateUrl: './sunburst.component.html',
  styleUrls: ['./sunburst.component.scss']
})
export class SunburstComponent implements OnInit {
  constructor() {}

  ngOnInit() {
    const myChart: Sunburst = Sunburst();
    myChart.data(sbdata)('sbChart');
  }
}

And the sunburst.component.html:

<div class="card" id="sbChart"></div>

Here are the sources of the sunburst-chart: https://github.com/vasturiano/sunburst-chart


Solution

  • Here I have a working solution with Angular 9 style.

    Install: "sunburst-chart": "^1.8.0" and if you want also "d3": "^5.15.0".

    import { Component, OnInit } from '@angular/core';
    import Sunburst from 'sunburst-chart';
    import * as d3 from 'd3';
    
    @Component({
      selector: 'app-sunburst',
      templateUrl: './sunburst.component.html',
      styleUrls: ['./sunburst.component.scss']
    })
    export class SunburstComponent implements OnInit {
      loading: boolean;
    
      @ViewChild('sbChart', { static: true }) sbChartEl: ElementRef;
    
      constructor() {}
    
      ngOnInit() {
        this.loading = true;
        const color = d3.scaleOrdinal(d3.schemePaired);
        const sbdata = {
          name: 'main',
          color: 'magenta',
          children: [
            {
              name: 'a',
              size: 1
            },
            {
              name: 'b',
              children: [
                {
                  name: 'ba',
                  size: 1
                },
                {
                  name: 'bb',
                  children: [
                    {
                      name: 'bba',
                      size: 1
                    },
                    {
                      name: 'bbb',
                      size: 1
                    }
                  ]
                }
              ]
            }
          ]
        };
    
        Sunburst()
          .data(sbdata)
          .size('size')
          .height(500)
          .showLabels(false)
          .tooltipContent((d, node) => `Size: <i>${node.value}</i>`)
          //.color(d => color(d.name))(document.getElementById('sbChart'));
          .color(d => color(d.name))(this.sbChartEl.nativeElement);
    
        this.loading = false;
      }
    }
    

    The sunburst.component.html file:

    <div [hidden]="loading">
      <div id="sbChart" #sbChart></div>
    </div>