How to implement D3 in Angular 2

I want to implement this code from d3.js into an angular 2 component, but I don't know how to call the js file in the ts file of the component. I found code for a line chart, with index.html and lineChart.js. How can I call javascript in ngAfterViewInitor afterViewInit.

An example of what the diagram looks like http://plnkr.co/edit/Jijnm8W4sRzAAsLMTvgV?p=preview

So I want to call it in the ts component of ngAfterViewInit.

Here is the code for the component:

import {Component, Directive, ViewChild, ElementRef, Renderer} from               'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

declare var d3: any;
declare var jQuery: any;
@Directive({

})
class H3 {}


@Component({
  selector: 'my-app',

})
export class D3 {

  constructor(public renderer: Renderer, public el: ElementRef){ }

  ngOnInit() {

  }


  ngAfterViewInit() {



  }

}
+3
source share
3 answers

You can use something like this:

declare var d3: any;

export class D3 {
  constructor(public renderer: Renderer, public el: ElementRef){ }

  ngOnInit() {

  }

  ngAfterViewInit() {
    var el:HTMLElement = this.el.nativeElement;
    var root = d3.select(el);

    root.append('svg')
    (...)
  }
}

See this question for more information:

+2
source
npm install --save d3

d3 package.json node_modules.

component.ts

import * as d3 from 'd3';

javascript component.ts

0

This is for d3-V4. I usually prefer d3-ng2-service . It is easy to install and use.

npm install d3-ng2-service --save

Add D3Service to providers in app.module.ts

In your .ts file, import the necessary D3 libraries, for example

import { D3Service, D3,
  Axis,
  Path,
  ScaleLinear,
  ScaleOrdinal,
} from 'd3-ng2-service';
Run codeHide result

After that, in the class constructor, save the d3 instance in the class variable

constructor( private _d3Service: D3Service) {
    this.d3 = this._d3Service.getD3();
    }
Run codeHide result

Now you can freely use the d3 variable to create svg objects

ngAfterViewInit(){
       this.buildSVG();
 }

buildSVG(): void {
      let d3=this.d3;
      var svg = d3.select("body").append("svg")
3                                .attr("width", 200)
4                                .attr("height", 200);
}
Run codeHide result
0
source

Source: https://habr.com/ru/post/1663935/


All Articles