Smokey Dawson
Smokey Dawson

Reputation: 9230

dynamically add classes to content coming from *ngFor from an array

Im not quite sure something like this is possible but say in my html component I have an ngFor like so..

<div *ngFor="let card of cards">
   ... stuff in here
</div>

now say I have an array of classNames like so

classNames = [
   'red',
   'yellow',
   'blue',
   'green'
]

and inside my *ngFor I have a div like so

<div *ngFor="let card of cards">
   <div [class]='...'>
      <div class="card">
      </div>
   </div>
</div>

basically what I want to happen is for every item in the ngFor give loop through the classNames array and dynamically add it to the incoming data so for example

say I have 6 items in cards so each card needs a classname so it loops through classNames and gives it a class so like this..

<div [class]='red'>
   <div class="card">
   </div>
</div>
<div [class]='yellow'>
   <div class="card">
   </div>
</div>
<div [class]='blue'>
   <div class="card">
   </div>
</div>
<div [class]='green'>
   <div class="card">
   </div>
</div>
<div [class]='red'>
   <div class="card">
   </div>
</div>
<div [class]='yellow'>
   <div class="card">
   </div>
</div>

and so on and so forth..

how could i accomplish something like this?

EDIT

component.html

<div class="card" *ngFor="let card of cards; let i = index">
   <div [class]="classNames[i%classNames.length]">
      ....
   </div> 
</div>

component.ts

export class...
  classNames = [
    'light-green',
    'dark-green',
    'aqua',
    'blue',
    'blue-purple',
    'purple',
    'purple-pink',
    'purple-orange'
  ];

Upvotes: 0

Views: 689

Answers (2)

manish
manish

Reputation: 1458

Instead of randomly applying any class to any card or deciding it on view based on some %, the best way, I believe would be read it from the Cards object itself, since it is logical to have all details of a card read from the card itself.

So that view is independent of those extra stuffs.

classNames = ['red','yellow','blue','green'];
cards = [{text: 1, class: this.classNames[0]},{text: 2, class: this.classNames[1]}];

your view should simply do its task (render)

<div *ngFor="let card of cards; let i = index">
  <div [class]="card.class">
    <div class="card">
      {{ card.text}}
    </div>
  </div>
</div>

Upvotes: 0

yurzui
yurzui

Reputation: 214017

You can leverage remainder (%) operator to achieve that:

<div *ngFor="let card of cards; let i = index">
   <div [class]="classNames[i%classNames.length]">
      <div class="card">
        {{ card }}
      </div>
   </div>
</div>

Ng-run Example

Update:

You should define array as follows:

classNames = [
   'light-green',
   'dark-green',
   'aqua',
   'blue',
   'blue-purple',
   'purple',
   'purple-pink',
   'purple-orange'
];

Note: i use = instead of :

Upvotes: 2

Related Questions