简体   繁体   中英

How to toggle class of multiple list items which displayed with *ngFor

I display list of different type with the *ngFor . What i need is when you click on any type, class .filtered should be toggled (if you click on typeA and then on typeB both should have class .filtered , if click again on the selected type, class should be removed).

Component

this.type = ["All", "typeA", "typeB", "typeC", "typeD", "typeE"]

HTML

<li> 
 <a id="filter">Type <i class="fa fa-caret-down" aria-hidden="true"></i></a> 
 <div class="drop-options tipoOption"> 
   <div *ngFor="let item of type;let i=index" 
    class="drop-option" 
    (click)="isClicked = i;" 
    [class.filtered]="isClicked==i"> 
    <span></span> 
    <p>{{ item }}</p> 
  </div> 
 </div> 
</li>

The way it works now, it toggle class only on one type, and deselect from others.

You could use an array:

<div *ngFor="let item of type;let i=index" 
    class="drop-option" 
    (click)="isClicked[i] = !isClicked[i];" 
    [class.filtered]="isClicked[i]">

This assumes the default for each array index starts as false.

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