...例如……

<div class="month" *ngFor="#item of myCollection; #i = index">
...
</div>

有可能做一些像……

<div class="month" *ngFor="#item of 10; #i = index">
...
</div>

...不诉诸于不优雅的解决方案,比如:

<div class="month" *ngFor="#item of ['dummy','dummy','dummy','dummy','dummy',
'dummy','dummy','dummy']; #i = index">
...
</div>

?


当前回答

这也可以像这样实现:

HTML:

<div *ngFor="let item of fakeArray(10)">
     ...
</div>

打字稿:

fakeArray(length: number): Array<any> {
  if (length >= 0) {
    return new Array(length);
  }
}

演示工作

其他回答

这是我试过的最简单的方法

你也可以在你的组件文件中创建一个数组,你可以用*ngFor指令调用它,返回一个数组。

就像这样....

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-morning',
  templateUrl: './morning.component.html',
  styleUrls: ['./morning.component.css']
})
export class MorningComponent implements OnInit {

  arr = [];
  i: number = 0;
  arra() {
    for (this.i = 0; this.i < 20; this.i++) {
      this.arr[this.i]=this.i;
    }
    return this.arr;
  }

  constructor() { }

  ngOnInit() {
  }

}

这个函数可以在你的html模板文件中使用

<p *ngFor="let a of arra(); let i= index">
value:{{a}} position:{{i}}
</p>

My-component.ts

numbers: number[] = [];

constructor() {
  this.numbers = new Array<number>(10)
}

My-component.html

<div *ngFor="let num of numbers; let i = index">{{ i }}</div>

在你的组件中,你可以定义一个number (ES6)数组,如下所示:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4]
    this.numbers = Array(5).fill(4); // [4,4,4,4,4]
  }
}

查看这个链接来创建数组:用最简洁的方法从1..JavaScript 20。

然后你可以用ngFor迭代这个数组:

@Component({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

或:不久

@Component({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}
<div *ngFor="let number of [].constructor(myCollection)">
    <div>
        Hello World
    </div>
</div>

这是一个在myCollection中重复相同次数的好方法。

如果myCollection是5,Hello World会重复5次。

下面是Angular的一些非常干净和简单的东西:

在.ts:

max = 10;    

. html:

<div *ngFor="let dummy of ','.repeat(max).split(','); index as ix">
   - {{ix + 1}}:
</div>