简体   繁体   中英

Angular 2 change ngFor items class knowing only it's index

I have a lot of buttons in my *ngFor , and I want that when someone click's on a button - it becomes active(it gets active class).

What I've done :

HTML :

<button 
  [ngClass]="{'activeBtn': buttActive }" 
  (click)="addDistrict(item);changeActive(i)" 
  *ngFor="let item of items; let i = index" 
  ion-button 
  #disable>
  {{item.name}}
</button>

TS : (changing all buttons class to active (i want to change only that one i clicked)

buttActive = false;
changeActive(i) {
  console.log(i);
  this.buttActive = !this.buttActive;
}

have a buttActive property in the object and change it

button [ngClass]="{'activeBtn': item.buttActive }"  (click)="addDistrict(item);changeActive(item,i)"  
*ngFor="let item of items; let i = index"     ion-button #disable>{{item.name}}</button>


 changeActive(item, i){
    console.log(i);
    item.buttActive = !item.buttActive;
  }

If you don't want to create a property on each item, then create a lastClickedIndex property in your Component class and set it with the index of the button that was clicked:

lastClickedIndex;
changeActive(i) {
  this.lastClickedIndex = i;
}

And in your template, check for the lastClickedIndex button based on index to apply the activeBtn class.

<button 
  *ngFor="let item of items; let i = index" 
  [ngClass]="(lastClickedIndex == i) ? 'activeBtn': ''" 
  (click)="addDistrict(item);changeActive(i)" 
  ion-button 
  #disable>
  {{item.name}}
</button>

That way you won't have to create a property on each item object. This will also take care of removing the class from the previously selected button when some other button is clicked.

Here's a StackBlitz for your ref.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM