Bruno
Bruno

Reputation: 23

How to pass ngFor index in ngClass

I'm trying to pass the ngFor with index inside ngClass to activate the correct class. I have tried different ways, but I have not been successful.

Here's the code:

<td *ngFor="let cell of row; let i = index" [ngClass]="{'col-tb-1-active' : classFocus.col1 , 'col-tb-1' : !classFocus.col1}">{{ cell.value }}</td>

In this case, where it has "1", I want to change the index. Would be something like:

<td *ngFor="let cell of row; let i = index" [ngClass]="{'col-tb-1-active' : classFocus.col1 , 'col-tb-1' : !classFocus.col1}">{{ cell.value }}</td>

I tried it that way, but it did not work:

<td *ngFor="let cell of row; let i = index" [ngClass]="{'col-tb-' + i + '-active' : 'classFocus.col' + i , 'col-tb-' + i : !'classFocus.col'+ i}">{{ cell.value }}</td>

Upvotes: 1

Views: 5978

Answers (4)

Peter Huang
Peter Huang

Reputation: 1198

<ng-container *ngFor="let item of list; let i = index">
    <tr [class]="'col'+i">{{item}}</tr>
</ng-container>

Upvotes: -1

KShewengger
KShewengger

Reputation: 8269

You can try it this way:

I have provided a Stackblitz Demo for your reference as well.

Avoid having it as classFocus.col + i, as it would not treat it as a variable with data on it.

Enclose them in a bracket [ ] if you want a dynamic className and its condition

Use conditional ternary operator (?) when dealing with 2 conditions that could either result in true or false

 <td *ngFor="let item of list; let i = index"
     [ngClass]="[classFocus['col' + i] ? 
                'col-tb-' + i + '-active' : 'col-tb-' + i]">
   {{ item }}
 </td>

Upvotes: 3

Simon K
Simon K

Reputation: 2857

I believe you are after the following:

<td *ngFor="let cell of row; let i = index" [class]="'col-tb-' + i + (classFocus['col' + i] ? '-active' : '')">{{ cell.value }}</td>

Upvotes: 1

Vignesh
Vignesh

Reputation: 1222

Try this

<td *ngFor="let cell of row; let i = index" [ngClass]="{'col-tb-' +{{ i }}+ '-active' : 'classFocus.col' + {{i }}, 'col-tb-' +{{ i }}: !'classFocus.col'+{{ i}}}">{{ cell.value }}</td

Upvotes: 0

Related Questions