突出显示数组中的所选项目并循环显示

时间:2018-05-25 15:47:31

标签: angular typescript components

我有"gameboard"模拟DnD游戏。它是基于回合的,但是这5个已经根据某个值进行了排序(从左到右)。但是现在我想强调一下那个转向它的玩家,并使用那些" next"和"之前"按钮循环通过它。这就是我所拥有的:

$rules = [
    'site/page/<page:\d+>/job/<job_id:\d+>/order-price/<min_price:\d+>/order-exp/<experience:\d+>/' => 'site/index'
];   

'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'suffix' => '/',
        'rules' => $rules,
    ],
]

$pagination = [
    'pageSize' => 1,
    'forcePageParam' => true,
    'pageSizeParam' => false,
    'params' => [
        'page' => $this->page,                        
        'job' => $this->job_id,
        'order-price' => $this->min_price,
        'order-exp' => $this->experience
    ],
];

我使用ngClass绑定它,但它没有显示:

<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;
 }
}

修改

由qUest给出的解决方案,由于我的CSS乱码而稍微修改了一下:

<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>

1 个答案:

答案 0 :(得分:1)

您可以使用简单的绑定轻松指定类:

// 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>

只要选择参与者,“选定”类就会被分配给div元素。