Saravana Manikandan
Saravana Manikandan

Reputation: 266

In Angular2 how to add a class to only the first row

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

Answers (4)

Igor Janković
Igor Janković

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

Christopher Moore
Christopher Moore

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:

  1. index The index of the current item in the iterable.
  2. first True when the item is the first item in the iterable.
  3. last True when the item is the last item in the iterable.
  4. even True when the item has an even index in the iterable.
  5. odd True when the item has an odd index in the iterable.

Upvotes: 11

Torsten Simon
Torsten Simon

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

Yoav Schniederman
Yoav Schniederman

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

Related Questions