2

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

3 Answers 3

1

Filter your data in component

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

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

Sign up to request clarification or add additional context in comments.

Comments

0

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;
  }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.