user8836786
user8836786

Reputation:

Angular 6 - Toggle Class on clicked items and toggle Class off other items

I have an Angular loop that's returning a a list of items from my database. Inside each of those items is an array (which is where the second *ngFor loop is.)

The second loop (*ngFor="let option of item.options) will have four results. When I click on the <li> with a class of question I want to add a class to highlight it. However, if I click on another <li> (for example, option 3 out of the 4), I would like to add a class to that one, but remove it from the first clicked <li>.

<ul>
  <li *ngFor="let item of items | async">
    <div>{{ item.title }}</div>
    <div>{{ item.question }}</div>
    <ul>
      <li class="question" *ngFor="let option of item.options">
        {{option}}
      </li>
    </ul>
  </li>
</ul>

It might be worth noting that I could have up to 15 items in the first loop *ngFor="let item of items | async"

Upvotes: 0

Views: 3907

Answers (2)

Eliseo
Eliseo

Reputation: 57939

the easy way is use a variable called e.g. "itemSelect" and use in *ngFor="..;let i=index", on click equal the variable to i and use [ngClass] or [className]. As you has two *ngFor you need an array of variables

<!--take acount the let i=index-->
<li *ngFor="let item of items | async;let i=index">
   ...
    <ul>
      <!--use itemSelect[i]-->
      <li [className]="j==itemSelect[i]?'question hightligth':'question'
          *ngFor="let option of item.options;let j=index" 
           (click)="itemSelect[i]=j">
            {{option}}
      </li>
    </ul>
<li>

Dont forget declare in your ts

itemSelect:number[]=[]

Upvotes: 2

Md. Abul Hasan
Md. Abul Hasan

Reputation: 23

You can do this by updating your html as follows

<ul>
  <li *ngFor="let item of items; let i = index">
    <div>{{ item.title }}</div>
    <div>{{ item.question }}</div>
    <ul>
    <li class="question"
        [class.active]="i == parentIndex && j == childIndex"
        (click)="setClickedRow(i, j)"
        *ngFor="let option of item.options; let j = index">
        {{ option }}
    </li>
    </ul>
  </li>
</ul>

Finally you need to update your ts file as follows

parentIndex : Number;
childIndex : Number;

setClickedRow(i,j){
 this.parentIndex=i;
 this.childIndex = j;
}

Upvotes: 0

Related Questions