Udit Gogoi
Udit Gogoi

Reputation: 705

How to use two different index variables inside the same ngFor in Angular 4

I am trying to get a different set of index numbers for each items printing as Saturday only. As soon as Saturday starts to print, my value should start from 0 and it should go on. The other options should have the same value numbers. How do I achieve that?

Here is my code in StackBlitz

Upvotes: 0

Views: 1212

Answers (2)

user4676340
user4676340

Reputation:

This is exactly what the modulo has been created for ...

But to be clear : you can't have two indexes in your array. That's not even logical : if you did, don't you think they would have the same value ?

Instead, use the modulo (it's its name in French, I don't know if it's translated or not) :

<div *ngFor="let item of items; let i = index">
  <span *ngIf="i % 7 === 5">It's Saturday !</span>
</div>

Snippet :

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
const month = [...days, ...days, ...days, ...days];

month.forEach((day, i) => {
  if (i % 7 !== 5) { return; }
  console.log(day);
});

EDIT ONE If you have an unordered array of days, the best way to "restart an index" is to split your array into several ones.

If you want to restart on saturdays, try something like this :

array=["monday","monday", "tuesday", "wednessday", "thursday", "friday", "saturday", "sunday", "saturday", "sunday"];
splitted = this.array.reduce((p, n) => {
  if (n === 'saturday') { p.push([n]); return p; }
  p[p.length - 1].push(n);
  return p;
}, [[]]);

    <p *ngIf="options != 'saturday' ">
      {{i}}. First category : Value{{i}}
      <p>
        <p *ngIf="options == 'saturday'" style="color:red">
          {{i}}. Saturday : Value{{i}}
        </p>
  </div>
</div>

Here is your updated stackblitz.

EDIT TWO I hope this is it this time ! Simply create a counter with a getter, and initialize the counter to zero once the lifecycle is done.

private counter;

get saturdayCounter() {
  return this.counter++;
}

ngAfterContentChecked() {
  this.counter = 0;
}
<p *ngIf="options == 'saturday'" style="color:red">
  {{i}}. Saturday : Value{{saturdayCounter}}
</p>

Here is a working stackblitz.

Upvotes: 2

Eliseo
Eliseo

Reputation: 57909

make a new array based in your "array"

let newArray:any[]=[];
let count:number=0;

this.array.forEach((a,index)=>{
   if (a=="saturday")
   {
     newArray.push({type:1,index:count});
     count++
   }
   else
     newArray.push({type:0,index:index});
}) 

Upvotes: 0

Related Questions