Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement D3 in Angular 2

Tags:

angular

d3.js

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



  }

}
like image 325
Sasa Geric Avatar asked May 04 '16 21:05

Sasa Geric


People also ask

Can D3 be used with angular?

D3 can load CSVs from your Angular application or a third-party URL and makes the data available as an array of objects in the resulting promise.

Is D3 js obsolete?

The JavaScript ecosystem has completely changed during this time, in terms of libraries, best practices and even language features. Nevertheless, D3 is still here. And it's more popular than ever.

What can d3js do?

D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.

Is D3 js easy?

Conclusion. D3. js is a very powerful, yet simple, JavaScript library that allows you to play with and bring life to documents based on data using HTML, CSS, and SVG. There are a lot of good resources available online to learn D3.


1 Answers

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:

  • Using D3.js with Angular 2
like image 109
Thierry Templier Avatar answered Sep 22 '22 20:09

Thierry Templier