Search code examples
angulararraylisthtml-listsngfor

How do I create an ordered list using angular?


Usually creating an ordered list is pretty simple but I am trying to do it in angular while using the *ngFor directive. The following code works like a charm except for the fact that it just says the number 1 next to each ordered list item in my resulting array instead of numbering them sequentially. I would like to make sure each item is numbered correctly ie( 1 2 3 4 etc.. instead of 1 1 1 1). How can I achieve this?

<div *ngFor="let item of result; let i=index"> <ol> <li *ngIf="i<3"> {{item.key}} appears {{item.value}} {{(item.value>1)? 'times' : 'time'}} </li> </ol> </div>
//currently outputs 1.bacon appears 3 times 1.pepperoni appears 3 times 1.beef appears 2 times


Solution

  • The problem is that you're looping around the root <div> so you're actually generating 3 <ol> instead of 3 <li> inside one <ol>. You need to loop around <li> but since you cannot have ngFor and ngIf on the same element you need to use <ng-container>. Something like this:

    <div >
      <ol>
       <ng-container *ngFor="let item of result; let i=index">
          <li *ngIf="i < 3">{{item.key}} appears {{item.value}} {{(item.value>1)? 'times' : 'time'}}</li>
       </ng-container>    
      </ol>
    </div>