2016-06-28 365 views
0

我看了一些答案,但沒有工作對我來說,我輸了...我用科爾多瓦,離子和角2對象不支持屬性或方法「的getAttribute」

這裏是我的HTML

<ion-col *ngFor="let value of myButtonsFirstRow" width-25><button #elem ptcolor (click)="volumeClick(elem)" attr.floatValue="{{value}}"> {{value | fraction}}</button></ion-col> 

這裏是我的打字稿

volumeClick(htmlElem: HTMLElement) { 
    this.volumeSelected = +htmlElem.getAttribute('floatValue'); 
} 

我想設置從我創建的屬性值(在我的HTML)。但看起來像我不能使用getAttribute方法。我的htmlElem已設置,但我沒有看到該方法,所以我知道我做錯了什麼,但我不知道是什麼!

由於

回答

1

是的,那是因爲elem是一種離子組分。所以我看到幾種方法來做到這一點:

1)不幸的是Button組件沒有公共方法/財產來獲取nativeElement/attribute。此代碼應工作:

volumeClick(elem: any) { 
    this.volumeSelected = +elem._elementRef.nativeElement.getAttribute('floatValue'); 
} 

2)獲得屬性另一種方式是在你的模板使用$event這樣的:

<button (click)="volumeClick($event)" attr.floatValue="{{value}}"> {{value}}</button> 

然後你的方法是這樣的:

volumeClick(event: any) { 
    this.volumeSelected = +event.currentTarget.getAttribute('floatValue'); 
} 

注意:我使用currentTarget,因爲Button組件有幾個孩子。

3)你可以只通過value點擊事件:

<button (click)="volumeClick(value)">{{value}}</button> 

volumeClick(value: any) { 
    this.volumeSelected = value; 
} 

還是有點簡單:

<button (click)="volumeSelected = value">{{value}}</button> 
+0

這就是我認爲的離子元素...即使按鈕元素與HTML相同哈哈。無論如何,我不會再爲那一個而墮落。你的答案#1是完美的!再次感謝 ! :) – theyouishere

0

模板變量的基準返回ElementRef。如果您要訪問的HTMLElement使用ElementRef.nativeElement

volumeClick(htmlElem: ElementRef) { 
    this.volumeSelected = +htmlElem.nativeElement.getAttribute('floatValue'); 
} 
+0

你不覺得'attr.floatValue'應與'[包裝] ' –

+2

無論是'[]'還是'{{}}'但都不是。 –

+0

這是我嘗試的第一件事情之一。它的工作,我有訪問getAttribute方法。但是,它並不像我沒有得到什麼屬性。我是否在getAttribute中使用了良好的語法? – theyouishere

相關問題