2016-01-10 43 views
4

我已經成功地角2(阿爾法44)與D3.js:如何D3.js與渲染整合API與角2

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

一切工作正常。但是ElementRef的Angular 2文檔聲明如下:

當需要直接訪問DOM時,使用此API作爲最後的手段。改爲使用Angular提供的模板和數據綁定。或者,您可以看看Renderer,它提供了即使在不支持直接訪問本地元素時也可以安全使用的API。依賴於直接的DOM訪問會在你的應用程序和渲染層之間產生緊密的耦合,這將導致無法將這兩者分開並將你的應用程序部署到web worker中。

現在的問題是如何將D3.js與Renderer API集成?

+1

您是否有時間觀看此視頻:使用Angular2和TypeScript創建d3組件(https://www.youtube.com/watch?v=x296y5mErWI)? –

+0

[使用D3.js與Angular 2]可能重複(http://stackoverflow.com/questions/33385500/using-d3-js-with-angular-2) –

回答

2

你也可以使用@ViewChild()Angular 2: how control <video> from component) 它不會有太大的區別,因爲這仍然是直接的DOM訪問,它將阻止服務器呈現並在web-workers中運行。但是像d3這樣的圖書館無論如何都沒有辦法。

+0

我同意。這是最後的手段之一,您唯一的選擇是直接訪問DOM – Zyzle