angular2 구성 요소에 D3 차트를 작성하려고합니다. D3 차트를 만들 링크를 클릭하면 새로운 인스턴스가 생성됩니다. 여러 개의 SVG 태그 복사본이 생성되는 HTML을 확인하십시오. 어떤 아이디어가 왜 일어나고 어떻게 피할 수 있습니까? D3 차트를 만들 때 링크를 클릭 할 때마다 기존 인스턴스를 지워야하며 새로운 차트 구성 요소를 만들어야합니다. 부모 컴포넌트의 새로운 인스턴스를 생성여러 개의 svg 요소가 생성되는 것을 방지하려면 어떻게해야합니까?
코드,
import { Component } from '@angular/core';
import { BubbleChart } from '../Charts/BubbleChart';
@Component({
template: `
<div id="divBubbleChart">
<bubble-chart></bubble-chart>
</div>
`,
directives: [BubbleChart]
})
export class CacheVisualization {
constructor() {
console.log("CacheVisualization component being called");
}
}
자식 D3 생성 요소에 ID를 할당 한 후 성분
import { Component, ViewEncapsulation } from '@angular/core';
import { HTTP_PROVIDERS, Http } from '@angular/http';
import { Configuration } from '../Configuration/Configuration';
declare var d3: any;
@Component({
selector: 'bubble-chart',
styleUrls: ['css/BubbleChart.css'],
providers: [Configuration, HTTP_PROVIDERS],
template: ``,
encapsulation: ViewEncapsulation.None
})
export class BubbleChart {
public resultData: any;
public chartData: any;
margin = 5;
diameter = 660;
constructor(private _Configuration: Configuration) {
console.log("In constructor of BubbleChartComponent");
this.DrawBubbleChart();
}
private DrawBubbleChart(): void {
console.log("Inside DrawBubbleChart in BubbleChartComponent");
//console.log(this.resultData);
var color = d3.scale.linear()
.domain([-1, 5])
.range(["hsl(152,80%,80%)", "hsl(228,30%,40%)"])
.interpolate(d3.interpolateHcl);
var pack = d3.layout.pack()
.padding(2)
.size([this.diameter - this.margin, this.diameter - this.margin])
.value(function (d) { return d.size; })
var svg = d3.select("body").append("svg")
.attr("width", this.diameter)
.attr("height", this.diameter)
.append("g")
.attr("transform", "translate(" + this.diameter/2 + "," + this.diameter/2 + ")");
var chart = d3.json(this._Configuration.BLUESKYDATACACHEAPI_GETEXTRACTORQUEUESLATEST, (error, root) => {
if (error) throw error;
var focus = root,
nodes = pack.nodes(root),
view;
var circle = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("class", function (d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
.style("fill", (d) => { return d.children ? color(d.depth) : null; })
.on("click", (d) => { if (focus !== d) zoom.call(this, d), d3.event.stopPropagation(); });
var text = svg.selectAll("text")
.data(nodes)
.enter().append("text")
.attr("class", "label")
.style("fill-opacity", function (d) { return d.parent === root ? 1 : 0; })
.style("display", function (d) { return d.parent === root ? "inline" : "none"; })
.text(function (d) { return d.name; });
var node = svg.selectAll("circle,text");
d3.select("body")
.style("background", "white")
//.style("vertical-align", "top")
//.style("background", color(-1))
.on("click",() => { zoom.call(this, root); });
zoomTo.call(this, [root.x, root.y, root.r * 2 + this.margin]);
function zoom(d) {
var focus0 = focus; focus = d;
var transition = d3.transition()
.duration(d3.event.altKey ? 7500 : 750)
.tween("zoom", (d) => {
var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + this.margin]);
return (t) => { zoomTo.call(this, i(t)); };
});
transition.selectAll("text")
.filter(function (d) { return d.parent === focus || this.style.display === "inline"; })
.style("fill-opacity", function (d) { return d.parent === focus ? 1 : 0; })
.each("start", function (d) { if (d.parent === focus) this.style.display = "inline"; })
.each("end", function (d) { if (d.parent !== focus) this.style.display = "none"; });
}
function zoomTo(v) {
var k = this.diameter/v[2]; view = v;
node.attr("transform", function (d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; });
circle.attr("r", function (d) { return d.r * k; });
}//end zoomTo
});//end chart
}//end DrawBubbleChart
}
, 그 상위의 HTML 태그 ID를 생성
"svg"태그가 아닙니다. 아래의 스냅 샷을 참조하십시오.
이것은 여러 개의 Angular2 구성 요소가 작성되는 것과 관련이 없습니다. 생성 된 것은 Angular2 외부이며 아마도 외부 D3 JS 라이브러리 (Angular2 구성 요소로 래핑 될 수 있음)에 의해 발생합니다. 새 차트를 만들기 전에 생성 된 차트를 삭제해야하지만, Angular2에 의해 발생하지 않았기 때문에 Angular2 메서드를 사용하여 수정할 수 없습니다. –
좋아, 어떻게 생성 된 차트를 여기에서 삭제합니까? 어떤 아이디어? 또는 새 인스턴스를 만들기 전에 DOM 요소를 찾아서 지워야합니까? – Krishnan
svg를 만들 때 권장합니다. 예 : **** var svg = d3.select ("body"). append ("svg") **** 원하는 ID를 지정하십시오. 예를 들어, 'mySVG '. ****. attr ('id', 'mySVG') ****과 마찬가지로 '#mySVG'가 제거되기 전에. 그래서 d3.select ('# mySVG'). remove(). 그러면 중복 문제가 해결됩니다. 분명히 무엇이든 추가하기 전에 ID를 주어야합니다. – thatOneGuy