Home > Net >  Angular SVG.js unable to reference svgCanvas to html element in component
Angular SVG.js unable to reference svgCanvas to html element in component

Time:02-21

My problem goes like this, I'm trying to implement the svg.js library into an angular component, the idea is that I can inject it into a div inside the component so I can manipulate it easily.

So to explain my problem in the component (is a child of the app-component) I have this div element in the html part of the component, the idea is to inject the svg element inside.

<div  #svgRenderer *ngIf="renderSvgElement" id="svgRenderer" name="svgRenderer"></div>

and then in the component.ts I have the method that is subscribed from the observable in the service that only execute this method.

  createContainerSVG() {
    this.renderSvgElement = true;
    this.svgCanvas = svg.SVG().addTo('#svgRenderer').size(200, 100); //error is located in the addTo
    this.svgCanvas.rect(100, 100).move(100, 50).fill('#f06');
  }

So the problem is that the addTo is supposed to receive a CSS selector but even so is only throwing me errors like "ERROR TypeError: Cannot read properties of null (reading 'put')".

What I tried is to make a viewChild directing to the id=svgRenderer and then using "nativeElement" to bring me the reference of the div resulting into a "ERROR TypeError: Cannot read properties of undefined (reading 'nativeElement')".

The thing that is working right now but is not what I want is to add the svgCanvas to the body, the idea is to hide the svg created behind something in the component then I export the svg element to pdf and then remove the svg component programmatically.

do I am forgetting how to call elements on angular? is something wrong with the way I'm doing it? I have to admit that I'm pretty new on Angular.

Also, I also accept alternatives that work well with angular as an answer but not ngx-svg, I need the final svg to be exported to pdf so it has to be hidden and created via typescript, not on the html as ngx-svg does.

CodePudding user response:

in the end I solved my own problem, if you see in my question I have this value this.renderSvgElement = true; ok it was supposed to make the panel appear if the value is true which it did but it wasn't being recognized by the viewChild even if it was rendered, so I took that check out and the element was recognized by the viewChild and I was able to use this.svgCanvas = svg.SVG().addTo(this.svgRenderer.nativeElement).size(200, 100); to attach my svg canvas to the element.

  • Related