Search code examples
htmlangularangular-ui-bootstrapngforng-style

ngStyle for specific condition


<h4 *ngFor="let x of textAddedList" 
    [ngStyle]="{backgroundColor:textAddedList.length>2?'grey':'transparent'}">
    {{x}}
</h4>

I want to apply the grey styling only after the 2 entries, but when I apply this logic it applies to all instead after 2nd line. Thanks in advance.


Solution

  • Work with index in *ngFor. As the index of array starts with 0, for the rows after the second row, the index are greater than 1:

    <h4
      *ngFor="let x of textAddedList; let i = index"
      [ngStyle]="{ backgroundColor: i > 1 ? 'grey' : 'transparent' }"
    >
      {{ x }}
    </h4>
    

    Sample StackBlitz Demo

    Output