Reputation: 23
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
Reputation: 1198
<ng-container *ngFor="let item of list; let i = index">
<tr [class]="'col'+i">{{item}}</tr>
</ng-container>
Upvotes: -1
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
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
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