typescript 单击添加类并删除切换类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46379373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Toggle class on click add class and remove
提问by sridharan
if i click item i need to add class name and if click same item need to remove the class for ngFor loop
如果我点击项目,我需要添加类名,如果点击相同的项目需要删除 ngFor 循环的类
<ion-item *ngFor="let x of statementresponse;let i=index" class="cust_delay delay" [ngClass]="{'active': selectedItem == x}" (click)="listClick($event, x)" >
</ion-item>
selectedItem:any;
listClick(event, newValue) {
console.log(newValue);
this.selectedItem = !newValue;.
}
回答by Mihailo
One of the ways you can do this is having your items have an "active"property, something like this:
您可以这样做的方法之一是让您的项目具有“活动”属性,如下所示:
items = [
{name:'one', active:false},
{name:'two', active:false},
{name:'three', active:false},
];
And inside the template represent them like this:
并且在模板内部表示它们是这样的:
<li *ngFor="let item of items"
(click)="toggleClass(item)"
[ngClass]="{'active': item.active}">{{ item.name }}</li>
And finally the toggleClass()method just toggles the active state of the clicked item:
最后,toggleClass()方法只是切换点击项的活动状态:
toggleClass(item){
item.active = !item.active;
}
Example
例子
回答by Vega
Try the following:
请尝试以下操作:
HTML
HTML
<ion-item *ngFor="let x of statementresponse;let i=index"
class="cust_delay delay"[class.active]="selectedItem == i"
(click)="selectedItem=i" >
{{x}}
</ion-item>
Typescript:
打字稿:
selectItem=-1
回答by LLL
You can store a boolean for that value somewhere. like in the object itself and then use
您可以在某处存储该值的布尔值。就像在对象本身中一样,然后使用
<ion-item [class.myClass]="item.myClass"></ion-item>
item.myClass
being the boolean
<ion-item [class.myClass]="item.myClass"></ion-item>
item.myClass
作为布尔值
and on click flip that value
然后单击翻转该值
item["myClass"] = !item["myClass"]
item["myClass"] = !item["myClass"]