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

后端 未结 9 493
甜味超标
甜味超标 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:43

    You can simply do :-

    {{"<li>Something</li>".repeat(5)}}
    
    0 讨论(0)
  • 2020-12-05 09:47

    Depending on the length of the wanted loop, maybe even a more "template-driven" solution:

    <ul>
      <li *ngFor="let index of [0,1,2,3,4,5]">
        {{ index }}
      </li>
    </ul>
    
    0 讨论(0)
  • 2020-12-05 09:48

    The better way to do this is creating a fake array in component:

    In Component:

    fakeArray = new Array(12);
    

    InTemplate:

    <ng-container *ngFor = "let n of fakeArray">
         MyCONTENT
    </ng-container>
    

    Plunkr here

    0 讨论(0)
  • 2020-12-05 09:57

    You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.

    In your component code :

    export class ForLoop {
      fakeArray = new Array(12);
    }
    

    In your template :

    <ul>
      <li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
    </ul>
    

    The index properties give you the iteration number.

    Live version

    0 讨论(0)
  • 2020-12-05 09:58
       queNumMin = 23;
       queNumMax= 26;
       result = 0;
    for (let index = this.queNumMin; index <= this.queNumMax; index++) {
             this.result = index
             console.log( this.result);
         }
    

    Range min and max number

    0 讨论(0)
  • 2020-12-05 09:59

    You can do both in one if you use index

    <div *ngFor="let item of items; let myIndex = index>
      {{myIndex}}
    </div>
    

    With this you can get the best of both worlds.

    0 讨论(0)
提交回复
热议问题