score:12

Accepted answer

this.renderer.createElement('svg') creates HTML element instead of SVGElement because Angular doesn't know you wanted svg:svg.

Try using this.renderer.createElement('svg', 'svg'), where second parameter is the Namespace. Every svg element must be created in the same way, e.g:

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

score:0

You have correctly added an svg element with a height and width to the view. But an svg element does not have a background-color attribute. You can think of it as the canvas on top of which you layer other elements that have shape and colour.

You need to add another element to this view to see anything. Remove the background-color attribute from the svg, then, as you have added the svg element to the view, you can use d3 to add, say, a rect to the view:

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

alternatively, you could just do the following:

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

Related Query

More Query from same tag