Как использовать модули в Angular 7 для условной привязки значения класса или атрибута в цикле ngFor?

Используя ngFor для цикла по массиву элементов, я хочу, чтобы элементы с индексом EVEN имели цвет фона, отличный от элементов с индексом ODD. Я смог добиться этого в VueJs, используя приведенный ниже код:

Я пробовал код Angular ниже, безуспешно:

 <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: этот код у меня работает в VueJs, но мне нужно добиться той же логики в 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>

person astroame    schedule 05.06.2019    source источник
comment
просто используйте css четное и нечетное свойство   -  person Kamil Naja    schedule 05.06.2019
comment
вы можете использовать в * ngFor let event = даже увидеть angular.io/api/common/NgForOf и ngClass [ngClass]="{even? 'text-center box bg-success':'text-center bg-info'}" или [ngClass]="{'text-center box bg-success':even,'text-center bg-info'}:!even"   -  person Eliseo    schedule 05.06.2019


Ответы (3)


ты можешь попробовать вот так

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

Попробуйте вот так:

<ion-card [style.color]="i % 2?'secondary': 'primary'">

Для цвета фона:

 <ion-card [style.background-color]="i % 2?'secondary': 'primary'">
person Adrita Sharma    schedule 05.06.2019

Что-то такое? https://stackblitz.com/edit/angular-fia7hx

<div *ngFor="let item of [1,2,3,4,5,6,7,8,9]; index as i">
    <p  [ngClass]="{greyClass: i%2 === 0}">
      {{item}}
    </p>
</div>

.greyClass {
    background-color: grey;
}
person DEVolkan    schedule 05.06.2019