javascriptangularsvgbindingforeignobject

Set position for foreignObject in Angular


Can't set position (x, y) for foreignObject in Angular.

I've tried like this:

<foreignObject width="65" height="50" x="{{position?.x}}" y="{{position?.y}}">
   <div class="container">works!</div>
</foreignObject>

and

<foreignObject width="65" height="50" [x]="position?.x" [y]="position?.y">
   <div class="container">works!</div>
</foreignObject>

but with bindings gets error:

Cannot set property x of [object SVGForeignObjectElement] which has only a getter

and it works if I set position like this:

<foreignObject width="65" height="50" x="100" y="100">
    <div class="container">works!</div>
</foreignObject>

How can I dynamically set position of foreignObject?


Solution

  • I found decision

    Needs add local reference to foreignObject

    <foreignObject width="65" height="50" #foreignFirst> <- here
       <div #container class="npz-container">works!</div>
    </foreignObject>
    

    Then in ts file needs add viewChild and attribute:

    @ViewChild('foreignFirst') foreignFirst: ElementRef;
    
    this.foreignFirst.nativeElement.setAttribute('x', this.position.x);
    this.foreignFirst.nativeElement.setAttribute('y', this.position.y);