5

I have successfully integrated Angular 2 (Alpha 44) with D3.js:

<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <script src="../node_modules/systemjs/dist/system.src.js"></script>
    <script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
    <script>
      System.config({packages: {'app': {defaultExtension: 'js'}}});
      System.import('app/app');
    </script>
  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

app.js:

/// <reference path="./../../typings/tsd.d.ts" />

import {Component, bootstrap, ElementRef} from 'angular2/angular2';

@Component({
  selector: 'my-app',
  template: '<h1>D3.js Integrated if background is yellow</h1>',
  providers: [ElementRef]
})
class AppComponent { 
  elementRef: ElementRef;

  constructor(elementRef: ElementRef) {
    this.elementRef = elementRef;
  }

  afterViewInit(){
    console.log("afterViewInit() called");
    d3.select(this.elementRef.nativeElement).select("h1").style("background-color", "yellow");
  }
}
bootstrap(AppComponent);

Everything is working fine. But Angular 2 documentation for ElementRef states the following:

Use this API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead. Alternatively you take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.

Now the question arises how to integrate D3.js with the Renderer API's?

Freego
  • 456
  • 7
  • 18
AsimRazaKhan
  • 2,154
  • 3
  • 22
  • 36
  • 1
    Do you have time to watch this video: Creating d3 components with Angular2 and TypeScript (https://www.youtube.com/watch?v=x296y5mErWI) ? – d.danailov Jan 10 '16 at 11:01
  • 1
    Possible duplicate of [Using D3.js with Angular 2](http://stackoverflow.com/questions/33385500/using-d3-js-with-angular-2) – Hongbo Miao Mar 25 '16 at 03:46

1 Answers1

2

You can also use @ViewChild() (Angular 2: how control <video> from component) It won't make much difference because this still is direct DOM access which will prevent server rendering and running in web-workers. But with libraries like d3 there is no way around anyway.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I'd agree. This is one of these last resort cases where your only option is direct access to the DOM – Zyzle Jan 10 '16 at 12:04