2017-10-04 107 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

當然,但它並沒有解決問題。這與我上面描述的完全相同。 –