Set position for foreignObject in Angular

144 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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);
3
On

I suggest, your ForeignObject has x and y input properties, you can set;

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

You can create x object as Input property at ForeignObject.Component.ts:

private _position:any;  

@Input()
public get x(){ return position};
    
public set x(position:any){
    this._position=position;
}