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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With