I have this "gameboard" which simulates a DnD game. It is turn based but these 5 have already been sorted (left to right) according to a certain value. But now I would like to highlight the player who's turn it is, and use those "next" and "previous" buttons to cycle through it. This is what I have:
<div class="heroWrapper">
<div class="image hero" *ngFor="let participant of participants">
<img [src]="participant.imageUrl"/>
<span class="HP">{{participant.hitPoints}}</span>
<span class="namePlayer" *ngIf="isHero(participant)">
{{getPlayerName(participant)}}</span>
<span class="nameHero">{{participant.name}}</span>
</div>
</div>
selectedParticipant: number = 0;
next(){
++this.selectedParticipant;
}
previous(){
if(this.selectedParticipant != 0){
--this.selectedParticipant;
} else {
this.selectedParticipant = this.participants.length -1;
}
}
I bound it using ngClass, but nothing it showing:
<div class="heroWrapper">
<div class="image hero" *ngFor="let participant of participants; index as i">
<img [src]="participant.imageUrl" [ngClass]="{selected:
selectedParticipant == participant[i]}"/>
<span class="HP">{{participant.hitPoints}}</span>
<span class="namePlayer" *ngIf="isHero(participant)">
{{getPlayerName(participant)}}</span>
<span class="nameHero">{{participant.name}}</span>
</div>
</div>
Edit
Solution as given by qUest, modified a bit due to my CSS mess:
<div class="heroWrapper">
<div class="image hero" *ngFor="let participant of participants; index as
i" [class]="i === selectedParticipant ? 'selected hero' : 'image hero'" >
<img [src]="participant.imageUrl" />
<span class="HP">{{participant.hitPoints}}</span>
<span class="namePlayer" *ngIf="isHero(participant)"> {{getPlayerName(participant)}}</span>
<span class="nameHero">{{participant.name}}</span>
</div>
</div>
You can easily assign the class with a simple binding:
// compare with participant
<div *ngFor="let p of participants" [class.selected]="p === selectedParticipant">
...
</div>
// compare with number
<div *ngFor="let p of participants; let i = index" [class.selected]="i === selectedParticipant">
...
</div>
Class "selected" will be assigned to the div element whenever participant is selected.