【问题标题】:set position for foreignObject in angular以角度设置foreignObject的位置
【发布时间】:2022-01-14 00:37:57
【问题描述】:

无法在角度中为 foreignObject 设置位置 (x, y)

我试过这样:

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

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

但使用绑定会出错:

无法设置只有 getter 的 [object SVGForeignObjectElement] 的属性 x

如果我这样设置位置,它会起作用:

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

如何将动态位置设置为 foreignObject?

【问题讨论】:

    标签: javascript angular svg binding foreignobject


    【解决方案1】:

    我建议,你的 ForeignObject 有 x 和 y 输入属性,你可以设置;

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

    您可以在ForeignObject.Component.ts 处创建 x 对象作为 Input 属性:

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

    【讨论】:

    • 感谢您的回答。它不起作用,得到同样的错误
    • 我编辑了我的答案你能控制这些吗?
    • 是的,它可以在角度组件中工作,但foreignObject是SVG标签you can read here
    【解决方案2】:

    我找到了决定

    需要添加对foreignObject的本地引用

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

    那么在ts文件中需要添加viewChild和属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2017-07-22
      相关资源
      最近更新 更多