簡體   English   中英

D3條形圖未在角度5中呈現

[英]D3 Bar chart is not rendering in angular 5

我正在嘗試以角度5渲染D3條形圖。我已經使用命令安裝了d3圖

npm install d3

但是,當我將其與角度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()生命周期掛鈎是使用D3選擇元素的最佳位置,因為此時,DOM已准備好用於當前組件。

ngAfterContentInit() {
d3.select(“p”).style(“color”, “red”);
}

如果app.component.html文件中有<p>標簽,則在瀏覽器完成加載app.component后, <p>標簽應為紅色。

解決“ this ”范圍

在Angular中,在.ts文件中,“此”對象用於引用成員變量和成員函數。 而在D3js中,“此”對象填充有選定的HTML元素。

考慮一種情況,我們要在app.component.html上的鼠標單擊位置繪制一個圓圈。 我們將圓的“半徑”保留為AppComponent類的成員變量。

解:

$event參數傳遞給代碼上的click事件處理程序

<svg width=”100%” height=”1200" class=”mySvg” (click)=”clicked($event)”>點擊事件處理程序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的紅色圓圈。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM