我已经成功地将 Angular 2(Alpha 44)与 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>
Run Code Online (Sandbox Code Playgroud)
应用程序.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);
Run Code Online (Sandbox Code Playgroud)
一切正常。但是 Angular 2 文档ElementRef
说明如下: …
我想从d3.js到angular 2组件实现这个代码,但我不知道如何将js文件调用到组件ts文件中.我找到了一些折线图代码,包括index.html和lineChart.js.如何在ngAfterViewInit
或中调用javascript afterViewInit
.
图表如何显示http://plnkr.co/edit/Jijnm8W4sRzAAsLMTvgV?p=preview
所以我想在ngAfterViewInit中的组件ts中调用它.
这是组件的代码:
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() {
}
}
Run Code Online (Sandbox Code Playgroud) 通过以下链接后
我知道我们不应该直接操纵DOM。因此,我开始探索使用角度4的Renderer2。
因此,我开始编写一些代码以将svg添加到DOM。以下是我的代码片段。
HTML代码
<div class="row">
<div class="col-12">
<div #myBarGraph id="host"></div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Component.ts
export class BarGraphComponent implements OnInit {
host:any;
svg:any;
@ViewChild('myBarGraph') myBarGraph:ElementRef;
constructor(private renderer:Renderer2) { }
ngOnInit() {
//some logic
}
// called on some drop down selection
teamSelection(){
//some logic
this.host = this.mybarGraph.nativeElement;
buildSVG();
}
buildSVG():void {
this.svg = this.renderer.createElement('svg');
this.renderer.setAttribute(this.svg,'width','600');
this.renderer.setAttribute(this.svg,'height','400');
this.renderer.setAttribute(this.svg,'background-color','blue');
this.renderer.appendChild(this.host,this.svg);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码能够将svg元素添加到DOM。但是令我惊讶的是,它实际上没有显示svg元素!。
我确实提到了以下问题
但到目前为止,我找不到合适的答案。
如上所示,svg存在于DOM中,但未显示在网页中。任何帮助将非常感激。