2016-08-18 3 views
0

angular2 구성 요소에 D3 차트를 작성하려고합니다. D3 차트를 만들 링크를 클릭하면 새로운 인스턴스가 생성됩니다. 여러 개의 SVG 태그 복사본이 생성되는 HTML을 확인하십시오. 어떤 아이디어가 왜 일어나고 어떻게 피할 수 있습니까? enter image description here 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"태그가 아닙니다. 아래의 스냅 샷을 참조하십시오. enter image description here

+0

이것은 여러 개의 Angular2 구성 요소가 작성되는 것과 관련이 없습니다. 생성 된 것은 Angular2 외부이며 아마도 외부 D3 JS 라이브러리 (Angular2 구성 요소로 래핑 될 수 있음)에 의해 발생합니다. 새 차트를 만들기 전에 생성 된 차트를 삭제해야하지만, Angular2에 의해 발생하지 않았기 때문에 Angular2 메서드를 사용하여 수정할 수 없습니다. –

+0

좋아, 어떻게 생성 된 차트를 여기에서 삭제합니까? 어떤 아이디어? 또는 새 인스턴스를 만들기 전에 DOM 요소를 찾아서 지워야합니까? – Krishnan

+1

svg를 만들 때 권장합니다. 예 : **** var svg = d3.select ("body"). append ("svg") **** 원하는 ID를 지정하십시오. 예를 들어, 'mySVG '. ****. attr ('id', 'mySVG') ****과 마찬가지로 '#mySVG'가 제거되기 전에. 그래서 d3.select ('# mySVG'). remove(). 그러면 중복 문제가 해결됩니다. 분명히 무엇이든 추가하기 전에 ID를 주어야합니다. – thatOneGuy

답변

1

작성중인 요소를 제거하려면 구성 요소를 제거 할 때 제거해야합니다. 각도 2는 OnDestorylyfecycle hook입니다. 그것을 구현하십시오. 내부에서 svg 요소를 제거합니다.

ngOnDestroy() { 
    // save the element on creation and.. 
    // remove element from body here 
} 
+0

나는 OnDestory()에서 @thatOneGuy가 제안한 논리를 결합했으며 정상적으로 작동했습니다 – Krishnan

0

해결 방법 1 :. SVG 요소가 이미 SVG 요소를 d3.select ("몸")를 작성하기 전에 존재하는지 확인하세요 ("SVG")를 추가합니다. 차트 업데이트 'UpdateDrawBubbleChart()'을 호출해야 새로운 기능을 만들기 : 새 SVG에게

var svg = d3.select('#mySVG').transition() 

해결 방법 2를 추가하는 대신 사용할 수있는 경우. BubbleChart 생성자에서 클래스의 인스턴스가 이미 존재하는지 확인하고 'UpdateDrawBubbleChart'를 호출하면이 함수에서 SVG 요소를 제거하거나 d3 전환을 사용합니다.

관련 문제