[英]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). 我的
*ngFor
有很多按钮,我希望当有人单击按钮时它会变为活动状态(它成为活动类)。
What I've done : 我所做的:
HTML : 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) TS :(将所有按钮类更改为活动(我只想更改我单击的那个按钮)
buttActive = false;
changeActive(i) {
console.log(i);
this.buttActive = !this.buttActive;
}
have a buttActive
property in the object and change it 在对象中具有一个
buttActive
属性并对其进行更改
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: 如果不想在每个项目上创建一个属性,则在Component类中创建一个
lastClickedIndex
属性,并使用单击按钮的索引进行设置:
lastClickedIndex;
changeActive(i) {
this.lastClickedIndex = i;
}
And in your template, check for the lastClickedIndex
button based on index
to apply the activeBtn
class. 然后在您的模板中,根据
index
检查lastClickedIndex
按钮以应用activeBtn
类。
<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. 这样,您将不必在每个item对象上创建一个属性。 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. 这是一个供您参考的StackBlitz 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.