chris01
chris01

Reputation: 12311

Angular, ngFor, index

How can I get the index i always counting the viewable output (1st line, 2ndline, ...) and not the data (data-line 1, data-line 4, ...)? So I would like to make it related to the ngIf instead of the order of data.

data: number []=[0,1,2,10,2,37,4,9,11];


<ul *ngFor="let d of data; let i = index;">
  <ng-container *ngIf="d%2==0">
    <li>Index={{i}} Data={{d}}</li>
  </ng-container>
</ul>

https://stackblitz.com/edit/angular-u7u4ru

I would like to have output

Index=0 Data=0
Index=1 Data=2
Index=2 Data=10
Index=3 Data=2
Index=4 Data=4

Upvotes: 2

Views: 1382

Answers (3)

Rashmi Kumari
Rashmi Kumari

Reputation: 530

Filter your data in component

this.data.filter(x => {
      if (x % 2 == 0)
        return x;
    });

Working demo https://stackblitz.com/edit/angular-feae8f

Upvotes: 1

Mike Bovenlander
Mike Bovenlander

Reputation: 5416

You should do this in the component itself not in the template.

Use the .map() operator to mod your data:

this.data = [0,1,2,10,2,37,4,9,11].map(x => { 
    if(x%2 == 0)
        return x;
})
// Remove all empty values.
.filter(n=>!isNaN(n));

stackblitz

Upvotes: 0

user4676340
user4676340

Reputation:

Use a counter and a getter with a hook on the last lifecycle event : stackblitz

export class AppComponent  {
  name = 'Angular';
  data: number []=[0,1,2,10,2,37,4,9,11];
  count = 0;

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

  ngAfterContentChecked() {
    this.count = 0;
  }
}

Upvotes: 0

Related Questions