Angular 2: How to write a for loop, not a foreach loop

后端 未结 9 494
甜味超标
甜味超标 2020-12-05 09:41

Using Angular 2, I want to duplicate a line in a template multiple times. Iterating over an object is easy, *ngFor="let object of objects". However, I

相关标签:
9条回答
  • 2020-12-05 09:59

    If you want to use the object of ith term and input it to another component in each iteration then:

    <table class="table table-striped table-hover">
      <tr>
        <th> Blogs </th>
      </tr>
      <tr *ngFor="let blogEl of blogs">
        <app-blog-item [blog]="blogEl"> </app-blog-item>
      </tr>
    </table>
    
    0 讨论(0)
  • 2020-12-05 10:09

    You could dynamically generate an array of however time you wanted to render <li>Something</li>, and then do ngFor over that collection. Also you could take use of index of current element too.

    Markup

    <ul>
       <li *ngFor="let item of createRange(5); let currentElementIndex=index+1">
          {{currentElementIndex}} Something
       </li>
    </ul>
    

    Code

    createRange(number){
      var items: number[] = [];
      for(var i = 1; i <= number; i++){
         items.push(i);
      }
      return items;
    }
    

    Demo Here

    Under the hood angular de-sugared this *ngFor syntax to ng-template version.

    <ul>
        <ng-template ngFor let-item [ngForOf]="createRange(5)" let-currentElementIndex="(index + 1)" [ngForTrackBy]="trackByFn">
          {{currentElementIndex}} Something
        </ng-template>
    </ul>
    
    0 讨论(0)
  • 2020-12-05 10:09

    you can use _.range([optional] start, end). It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range() method.

    Example:

    CODE

    var dayOfMonth = _.range(1,32);  // It creates a new list from 1 to 31.
    

    //HTML Now, you can use it in For loop

    <div *ngFor="let day of dayOfMonth">{{day}}</div>
    
    0 讨论(0)
提交回复
热议问题