Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

After going through the below link

Using D3.js with Angular 2

I understood that we should not be manipulating DOM directly. So I started exploring to use Renderer2 of angular 4.

So I started to write some code to add svg to DOM. Below are the snippets of my code.

HTML code

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

The above code is able to add the svg element to the DOM. But to my surprise, it actually not displaying the svg element!.

I did refer to the following questions

  1. Angular2 Renderer: Svg rect is rendered but not showing in page
  2. Angular2 does not render SVG in runtime

But I couldn't find the proper answer so far.

Below is a screenshot of the problem problem

As you can see above, svg is present in DOM, but it is not displayed in web page. Any help would be much appreciated.

like image 875
Srinivas Valekar Avatar asked Nov 24 '17 20:11

Srinivas Valekar


1 Answers

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)
like image 123
mvnukov Avatar answered Oct 05 '22 14:10

mvnukov