2017-02-28 27 views
0

如果我點擊playNote(note) function,但它會在ngfor循環中全部更改[name] =「myIcon」。 我只是想改變點擊一個...在角2和離子2 * ngfor,如果我點擊任何一個元素它反映了所有?

home.html的

<ion-item color="theme" class="note-block" *ngFor="let note of notes; let i = index" > 
     <button class="action-btn" ion-button icon-left clear small (click)="playNote(note)"> 
     <ion-icon color="darker" [name]="myIcon"></ion-icon> 
     </button> 
</ion-item> 

home.ts

myIcon: string = "play"; 


playNote(note){ 
    if(this.myIcon === "play"){ 
     this.myIcon = "pause" 
    } 
    else if(this.myIcon === "pause"){ 
     this.myIcon = "play"; 
    } 
} 
+0

請看看我的更新回覆 – mickdev

回答

0

你有兩種可能性:

第一一,你可以像這樣定義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] 
} 
+0

如果我想發揮myIcon與戲劇價值......有可能嗎? –

+0

你可以創建一個函數來填充你的數組,但在模板中啓動它更簡單'[name] =「myIcon [note] ='play'」'(我想這個note是一個標識符,用來代替note.id if它是一個對象) – mickdev

+0

是它的一個對象。所以我用myIcon [note.id] ---如果我安慰它改變myIcon值,但在模板中它不會改變....... :( –