Toggle class on click add class and remove

2019-04-11 14:23发布

if i click item i need to add class name and if click same item need to remove the class for ngFor loop

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

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-11 14:41

Try the following:

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

StackBlitz

查看更多
再贱就再见
3楼-- · 2019-04-11 14:51

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(item){
  item.active = !item.active;
}

Example

查看更多
一纸荒年 Trace。
4楼-- · 2019-04-11 14:56

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

and on click flip that value

item["myClass"] = !item["myClass"]

查看更多
登录 后发表回答