Search code examples
angularangular-template

How to use Modules in Angular 7 to conditionally bind a class or attribute value in ngFor loop?


Using ngFor to loop through an array of items, i want items with an EVEN index to have a different background color from items with an ODD index. i was able to achieve this in VueJs using the code below:

I have tried the Angular Code below, No Success:

 <ion-col  *ngFor="let item of [].constructor(50); let i = index" >

               <ion-card [attr.color]="{'secondary': i % 2, 'primary': !(i % 2)}">

</ion-card>
</ion-col>

VueJs Code: this code works for me in VueJs but i need to achieve this same logic in Angular 7

<div v-for="(itemforsale, index) in filteredListMainitemsforsale">

<div :class="{'box bg-success text-center': index % 2, 'box bg-info text-center': !(index % 2)}" >


</div>

</div>

Solution

  • you can try like this

    <ion-col  *ngFor="let item of [].constructor(50); let i = index" >
         <ion-card [ngStyle]="{'color': i % 2 == 0 ? 'secondary' : 'primary'}">
         </ion-card>
    </ion-col>