Home > Mobile >  How to print item position of rendered element Angular?
How to print item position of rendered element Angular?

Time:10-24

So, I have a list of items. I like to print only in the list who has a length of more than 0.

  lists = [
    {
      item: 1,
      length: 4,
    },
    {
      item: 2,
      length: 0,
    },
    {
      item: 3,
      length: 3,
    },
    {
      item: 4,
      length: 0,
    },
    {
      item: 5,
      length: 3,
    },
  ];

Currently, It is showing the array index of list!

<ul *ngFor="let list of lists; let i = index">
  <li *ngIf="list.length">{{ list.item }} INDEX #{{ i }}</li>
</ul>

Current output:

  • 1 INDEX #0
  • 3 INDEX #2
  • 5 INDEX #4

But I am looking for a solution so that the expected result should be like

  • 1 INDEX #0
  • 3 INDEX #1
  • 5 INDEX #2

CodePudding user response:

You could filter lists and then run it with ngFor:

get filteredList(): TheTypeOfTheList[] {
  return this.lists.filter(l => l.length);
}
<ul *ngFor="let list of filteredList; let i = index">
  <li *ngIf="list.length">{{ list.item }} INDEX #{{ i }}</li>
</ul>

Output would be

// 1 INDEX #0
// 3 INDEX #1
// 5 INDEX #2
  • Related