5

I want to implement this code from d3.js to angular 2 component, but i don't know how to call js file into component ts file. I have found some code for line chart, with index.html and lineChart.js. How can I call javascript in ngAfterViewInit or afterViewInit.

Example how chart looks like http://plnkr.co/edit/Jijnm8W4sRzAAsLMTvgV?p=preview

So I want to call this in component ts in ngAfterViewInit.

Here is code for 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() {



  }

}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
Sasa Geric
  • 57
  • 1
  • 1
  • 4

4 Answers4

3

You could use something like that:

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 details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Forgive me a stupid follow-up question from a Angular-newbie: Are there major changes towards Angular 6? – B--rian Aug 23 '18 at 07:02
2
npm install --save d3

check d3 version in package.json and check it in node_modules too.

then, in the component.ts, import it as below

import * as d3 from 'd3';

Write your javascript codes in component.ts class

2

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

npm install d3-ng2-service --save

Add D3Service to the providers in the app.module.ts

In your .ts file import the necessary D3 libraries like

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

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

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

Now you can freely use the d3 variable to build 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);
}
deerishi
  • 527
  • 7
  • 5
0

Please follow the following 3 steps

step 1: install D3 and the D3 type definitions from npm.

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

step 2: import d3 inside the ts file

import * as d3 from 'd3';

step 3: implement the logic

For reference

Anand Raja
  • 2,676
  • 1
  • 30
  • 35