Need to change height of foreignObject inside svg

701 Views Asked by At

I need to change height of foreignObject in svg dynamically. I have to use foreignObject as I need html elements inside it. (I'm working with ngx-graph).

<foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Data.length)" class="{{ checkIfSourceNode(node) }}">
...
</foreignObject>

I'm getting error:

TypeError: Cannot set property height of [object SVGForeignObjectElement] which has only a getter

Please help!

2

There are 2 best solutions below

0
Matthieu Riegler On BEST ANSWER

In your case you can just set the height attribute to its value :

<foreignObject x="1" y="1" width="335" [attr.height]="foreignObjHeight(node.Data.length)" ">
0
JohnnyB On

You can use an ResizeObserver. In the example below, the child element (childspan) of the foreignObject element is being observered for changes in size, at which point the foreignObject width and height are updated

let foreignbox, childspan;
function foreignsize() {
    if ( !foreignbox ) foreignbox = document.getElementById("forobjquestion");
    if ( !childspan ) childspan = document.getElementById("inputhtml");
    let spanBB = childspan.getBoundingClientRect();
    if ( foreignbox ) {
      foreignbox.setAttribute("width", spanBB.width/5); 
      foreignbox.setAttribute("height", spanBB.height/5); 
    }
  }
new ResizeObserver(foreignsize).observe(parentspan);

HTML

<foreignObject id="forobjquestion" x="0" y="0" width="100" height="100" xmlns="http://www.w3.org/2000/svg" >
    <span id="parentspan" >
        <xhtml:span id="inputhtml" >
            <xhtml:p id="mypid">123</xhtml:p>
        </xhtml:span>
    </span>
</foreignObject>