Reputation: 266
I want to add a css class based on certain conditions.
In the below code I want to add RowHeaderCSS
class to the first row of the table, but it does work. Can anyone help me on this?
<tr *ngFor="let dataObject of dataCollection;let isFirstRow=(index==1?true:false)" [ngClass]="{'RowHeaderCSS':isFirstRow)}">
<td scope="row">{{dataObject.SNO}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH01}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH02}}</td>
</tr>
Upvotes: 5
Views: 5541
Reputation: 5532
<tr *ngFor="let dataObject of dataCollection; let i = index" [ngClass]="{ i == 0 ? 'RowHeaderCSS' : ''}">
<td scope="row">{{dataObject.SNO}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH01}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH02}}</td>
</tr>
Upvotes: 0
Reputation: 3099
Angular has the local variable first
for all ngFor
loops which will do what you want
<tr *ngFor="let dataObject of dataCollection; let isFirstRow=first" [ngClass]="{'RowHeaderCSS' : isFirstRow}">
<td scope="row">{{dataObject.SNO}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH01}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH02}}</td>
</tr>
https://angular.io/api/common/NgForOf
Local Variables
NgFor provides several exported values that can be aliased to local variables:
index
The index of the current item in the iterable.first
True when the item is the first item in the iterable.last
True when the item is the last item in the iterable.even
True when the item has an even index in the iterable.odd
True when the item has an odd index in the iterable.
Upvotes: 11
Reputation: 413
Just a slightly different syntax:
<tr *ngFor="let dataObject of dataCollection; let i=index" [class.RowHeaderCSS]="i==0">
<td scope="row">{{dataObject.SNO}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH01}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH02}}</td>
</tr>
Upvotes: 0
Reputation: 5391
<tr *ngFor="let dataObject of dataCollection;let [ngClass]="{'RowHeaderCSS':isFirstRow(index))}">
<td scope="row">{{dataObject.SNO}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH01}}</td>
<td Overdue-Bucket-Template>{{dataObject.MONTH02}}</td>
</tr>
isFirstRow(index: number) : boolean{
return index === 1;
}
Upvotes: 0