After going through the below link
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
- Angular2 Renderer: Svg rect is rendered but not showing in page
- Angular2 does not render SVG in runtime
But I couldn't find the proper answer so far.
Below is a screenshot of the 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.