2017-10-04 47 views
0

我使用的是Angular的4.4.4版本。在我app.component.html我有这样的代码如何更新Angular 4中的SVG元素属性?

<button class="btn btn-primary" (click)="updatePosition()">Up</button> 
    <svg id="svg"> 
     <image xlink:href="../assets/map.png" x="0" y="0" height="420px" width="420px"/> 
    </svg> 

我想按下按钮时,动态更新xy值。我尝试了各种方法来做到这一点,没有结果。

例如我用属性绑定[style.x.px]="variableX"定义x位置,但尽管按下按钮并更新variableX值没有发梗所以看起来我还是要更新x位置。通常情况下,我会用简单的JavaScript来定位该图像,并对其执行el.setAttribute('x', value),但在角度上它不是那么简单,或者仅仅因为某种原因不起作用。

任何人都可以帮忙吗? :)

+1

属性绑定不工作,因为它只是将它的初始值。它不检查它的变化。你有没有尝试过使用双向绑定? –

+0

我可能会,但我寻求更好的解决方案来访问这些元素。我将不得不做一些更加紧凑的操作。 –

+0

'[风格。 ]'绑定到'style'绑定的设置值。 'x.px'不是一个有效的CSS属性,所以它什么也不做。你尝试绑定到'[attr.x]'而不是(['attr.x] =“variableX”')? – naeramarth7

回答

1

如果你只是想一个办法来处理图像的X和Y CSS属性,我会用两种:

NgStyle指令来动态地得到你想要的,像这样的任何值:

<button class="btn btn-primary" (click)="updatePosition()">Up</button> 
<image xlink:href="../assets/map.png" height="420px" width="420px [ngStyle]="style" /> 

position = { 'x': '0', 'y': '0' }; 
//you can also add any other css properties to this like width and height 
get style() { 
    return this.position; 
} 
updatePosition() { 
    this.position = { 'x': '10px', 'y': '10px' }; //however you update the values 
} 

或者使用一个本地ElementRef@ViewChild,并直接在您的TS操纵nativeElement像这样:

<button class="btn btn-primary" (click)="updatePosition()">Up</button> 
<image xlink:href="../assets/map.png" height="420px" width="420px" #image/> 

@ViewChild('image') image: ElementRef; 
updatePosition() { 
    this.image.nativeElement.style.x = '10px'; //however you update the values 
    this.image.nativeElement.style.y = '10px'; //however you update the values 
} 

如果你这样做,确保你从“@ angular/core”导入ViewChild

我还没有在plunkr或任何测试过,但我相信他们都应该工作。

+0

它解决了我的问题。我会用你的方法来改进我的脚本。但是,你能解释一下这个“get style()”的工作原理吗?它会自动更新元素的比例吗? –

+1

'get style()'是一个get访问器。它与任何常规函数基本相同,除了get访问器必须返回一些值。这就是为什么当你在html的'ngStyle'指令中使用它时,你应该使用'[ngStyle] =“style”'而不是'[ngStyle] =“style()”'。因为get访问器必须返回一个值,所以你不用括号就可以调用它,它的“值”就是它返回的值。并且由于get访问器本质上是一个函数,所以将其与'[ngStyle]'指令放在一起使得它“监视”它返回的值。 –

0

为了绑定到SVG元素属性在角度2中,您必须为它们添加attr。,e。摹:

<svg> 
    <circle [attr.r]="myRadius" cx="50" cy="50"></circle> 
</svg> 

这是一个伟大的博客解释角2与SVG的绑定问题:https://500tech.com/blog/all/svg-in-angular-2/

+0

当然,但它并没有解决问题。这与我上面描述的完全相同。 –

相关问题