LearnToday
LearnToday

Reputation: 2902

Changing class in div at some iteration

Basically this is what I want to achieve:

 <div  class="animations-player">
 <div class="block pink" id="block1">1</div>
<div class="block pink" id="block2">2</div>
 <div class="block yellow" id="block3">3</div>
<div class="block yellow" id="block4">4</div>
 <div class="block blue" id="block5">5</div>
<div class="block blue" id="block6">6</div>...
</div>

With the following function:

 createRange(len=32) {
    let arr = [];
    for(let i = 0; i < len ; i++) {
      arr.push(i);
    }
    return arr;
  }

 <div *ngFor="let item of createRange(32)">
  <div *ngIf="item>0" class="block pink" id="block{{item}}">{{item}}</div>
 </div>

I will get this:

 <div  class="animations-player">
 <div class="block pink" id="block1">1</div>
<div class="block pink" id="block2">2</div>
 <div class="block pink" id="block3">3</div>
<div class="block pink" id="block4">4</div>
 <div class="block pink" id="block5">5</div>
<div class="block pink" id="block6">6</div>...
</div>

This result has just the class of 'pink'. How to I get this to manipulate the class to 'blue' or 'yellow'?

Upvotes: 2

Views: 40

Answers (1)

Pace
Pace

Reputation: 43817

I don't know what your rules are for picking colors. You could add to your controller:

getColorForBlock(index) {
  if (index % 6 < 2) {
    return "pink";
  } else if (index % 6 < 4) {
    return "yellow";
  } else {
    return "blue";
  }
}

And then in your template:

<div *ngFor="let item of createRange(32)">
  <div *ngIf="item>0" [ngClass]="getColorForBlock(item)" class="block" id="block{{item}}">{{item}}</div>
</div>

Upvotes: 2

Related Questions