你有兩種可能性:
第一一,你可以像這樣定義myIcon
myIcon: string[] = [];
然後
playNote(note){
if(this.myIcon[note] === "play"){
this.myIcon[note] = "pause"
}
else if(this.myIcon[note] === "pause"){
this.myIcon[note] = "play";
}
}
在模板
<button class="action-btn" ion-button icon-left clear small (click)="playNote(note)">
<ion-icon [name]="myIcon[note.id]?myIcon[note.id] : myIcon[note.id] = 'play'"></ion-icon> <!-- default value to play -->
</button>
第二個,創建一個包裝組件(名單注)單注組件。您的所有單品都會有不同的範圍,使您可以在單個項目組件安全使用方法,因爲它:
playNote(note){
if(this.myIcon === "play"){
this.myIcon = "pause"
}
else if(this.myIcon === "pause"){
this.myIcon = "play";
}
}
這些都是未經測試的代碼。有些調整可能需要 這裏是一個工作plunker http://plnkr.co/edit/BOqB37AQkbySrzzDS5Vy?p=preview
編輯:這是一個快速解決 http://plnkr.co/edit/SVy8IkHxnKCDb4yA52HO?p=preview
在這個例子中,我使用布爾
模板:
<ion-item *ngFor="let note of notes; let i = index">
<h2>{{note.name}}</h2>
<button class="action-btn" ion-button icon-left clear small (click)="playNote(note)">
<ion-icon *ngIf = "!myIcon[note.id]" [name]="'play'"></ion-icon>
<ion-icon *ngIf = "myIcon[note.id]" [name]="'pause'"></ion-icon>
</button>
</ion-item>
在組件
myIcon: boolean[] = [];
playNote(note){
this.myIcon[note.id] = !this.myIcon[note.id]
}
請看看我的更新回覆 – mickdev