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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With