Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle class on click add class and remove

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;.
}
like image 772
sridharan Avatar asked Sep 23 '17 12:09

sridharan


People also ask

How do you add and remove a class on toggle?

jQuery toggleClass() Method The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.

How do I add and delete class on click?

jQuery toggleClass() Method Using the jQuery toggleClass() can add or remove one or more classes from the selected html elements. Incase if the selected html element already has the class, then it is removed. if an element does not have the class, then it is added.

How do you toggle with multiple classes?

Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.

How do you toggle between classes in HTML?

Toggle Class Toggle between adding a class name to the div element with id="myDIV" (in this example we use a button to toggle the class name).


2 Answers

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

like image 160
Mihailo Avatar answered Oct 21 '22 05:10

Mihailo


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

like image 21
Vega Avatar answered Oct 21 '22 05:10

Vega