Shounak
Shounak

Reputation: 15

Need to change height of foreignObject inside svg

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!

Upvotes: 0

Views: 907

Answers (2)

JohnnyB
JohnnyB

Reputation: 79

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>

Upvotes: 0

Matthieu Riegler
Matthieu Riegler

Reputation: 54569

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)" ">

Upvotes: 2

Related Questions