Sasa Geric
Sasa Geric

Reputation: 57

How to implement D3 in Angular 2

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() {



  }

}

Upvotes: 5

Views: 12676

Answers (4)

Anand Raja
Anand Raja

Reputation: 3126

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

Upvotes: 0

deerishi
deerishi

Reputation: 647

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);
}

Upvotes: 2

user7803780
user7803780

Reputation:

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

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202346

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:

Upvotes: 3

Related Questions