我正在尝试以 Angular 5渲染D3条形图。我已经使用命令安装了d3图
npm install d3
但是当我将它与 Angular 5 一起使用时,图表不会被渲染。 我的 Html 代码是:
<button (click)= 'getGraph()'>show</button>
<div class="chart">
</div>
我的 ts 文件:
import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent{
data= [10,20,30,40,50,60]
constructor()
{
}
ngOnInit() {
}
getGraph() {
d3.select(".chart")
.selectAll("div")
.data(this.data)
.enter()
.append("div")
.style("width", function(d) { return d + "px"; })
.text(function(d) { return d; });
}
}
我的 CSS 文件:
.chart div {
font: 10px sans-serif;
background-color: red;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
这些值显示在不同的位置,但没有形成图表。执行过程有没有什么问题。相同的代码在纯 JS 中运行。
这是 stackblitz 中的: https://stackblitz.com/edit/angular-rxgsv6?embed=1&file=src/app/app.component.html
注意:我从此官方链接获取了代码:https://scrimba.com/p/pEKMsN/cast-1953
在纯 JS 中工作正常
答案:在全局CSS而不是组件CSS中编写样式标签修复了这个问题
最佳答案
将 D3js 与 Angular 集成并开始利用 D3js 的强大功能构建 SPA 非常容易。
步骤:
使用 angular/cli 创建新的 Angular 项目
ng new d3-ng5-demo
创建新项目并安装依赖项后,安装 D3js
npm install d3
导入 D3 并开始在您的组件中使用它。例如,在app.component.ts文件中导入“d3”,如下所示:
import * as d3 from “d3”;
使用 d3js 选择 HTML 元素进行数据连接操作/DOM 操作。 ngAfterContentInit()
生命周期钩子(Hook)是使用 D3 选择元素的最佳位置,因为此时,DOM 已准备好用于当前组件。
ngAfterContentInit() {
d3.select(“p”).style(“color”, “red”);
}
如果您有<p>
浏览器加载完 app.component 后,app.component.html 文件内的标记 <p>
标签颜色为红色。
正在解决“this
” 范围
在 Angular 中,.ts 文件内的“this”对象用于引用成员变量和成员函数。而在 D3js 中,“this”对象由选定的 HTML 元素填充。
考虑一个场景,我们想要在 app.component.html 上的鼠标单击位置上绘制圆圈。我们将圆的“半径”保留为AppComponent类的成员变量。
解决方案:
通过 $event
标签上单击事件处理程序的参数
<svg width=”100%” height=”1200" class=”mySvg” (click)=”clicked($event)”>
Click 事件处理程序 inside.ts:
clicked(event: any){
d3.select(event.target).
append('circle').
attr('cx' , event.x).
attr('cy' , event.y).
attr('r' , this.radius).
attr('fill' , 'red')
}
就是这样!在浏览器中,如果您单击 <svg>
中的任意位置标签;您将看到在鼠标位置绘制了半径为 10 的红色圆圈。
关于javascript - D3 条形图未以 Angular 5 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51569555/