繁体   English   中英

使用d3 js时,Renderer2不渲染SVG元素 - Angular 4

[英]Renderer2 does not render SVG element while using d3 js - Angular 4

通过以下链接后

将D3.js与Angular 2一起使用

我明白我们不应该直接操纵DOM。 所以我开始探索使用角度4的Renderer2。

所以我开始编写一些代码来将svg添加到DOM中。 以下是我的代码的片段。

HTML代码

<div class="row">
 <div class="col-12">
   <div #myBarGraph id="host"></div>
 </div>
</div>

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); 
 }
}

上面的代码能够将svg元素添加到DOM。 但令我惊讶的是,它实际上没有显示svg元素!

我确实参考了以下问题

  1. Angular2渲染器:渲染了Svg rect但未在页面中显示
  2. Angular2不会在运行时呈现SVG

但到目前为止我找不到合适的答案。

以下是问题的屏幕截图 问题

如您所见,svg存在于DOM中,但它不会显示在网页中。 任何帮助将非常感激。

this.renderer.createElement('svg')创建HTML元素而不是SVGElement,因为Angular不知道你想要svg:svg。

尝试使用this.renderer.createElement('svg', 'svg') ,其中第二个参数是命名空间。 必须以相同的方式创建每个svg元素,例如:

let rect = this.renderer.createElement('rect', 'svg')
this.renderer.appendChild(svg, rect)

您已正确地向视图添加了具有高度和宽度的svg元素。 但是svg元素没有background-color属性。 您可以将其视为画布,在其上层叠其他具有形状和颜色的元素。

您需要在此视图中添加另一个元素才能看到任何内容。 从svg中删除background-color属性,然后,当你将svg元素添加到视图中时,你可以使用d3为视图添加一个rect:

d3.select(this.svg)
  .append('rect')
  .attr('x', 0)
  .attr('y', 0)
  .attr('width', 600)
  .attr('height', 400)
  .attr('fill', 'blue');

或者,您可以执行以下操作:

@Component({
  selector: 'bar-chart',
  template: `
    <div class='bar-chart' #barChart></div>
  `
})
export class BarChartComponent implements OnInit {

  @ViewChild('barChart')
  public chart: ElementRef;

  public svg: any;

  private width: number = 600;
  private height: number = 400;

  ngOnInit() {
    this.svg = d3.select(this.chart.nativeElement)
      .append('svg')
      .attr('width', this.width)
      .attr('height', this.height);

    this.svg
      .append('rect')
      .attr('x', 0)
      .attr('y', 0)
      .attr('width', this.width)
      .attr('height', this.height)
      .attr('fill', 'blue');
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM