...例如……

<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>

?


当前回答

<div *ngFor="let number of [].constructor(myCollection)">
    <div>
        Hello World
    </div>
</div>

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

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

其他回答

你可以使用lodash:

@Component({
  selector: 'board',
  template: `
<div *ngFor="let i of range">
{{i}}
</div>
`,
  styleUrls: ['./board.component.css']
})
export class AppComponent implements OnInit {
  range = _.range(8);
}

我没有测试代码,但它应该工作。

你也可以用like that

export class SampleComponent {
   numbers:Array<any> = [];
   constructor() {
      this.numbers = Array.from({length:10},(v,k)=>k+1);
   }
}

HTML

<p *ngFor="let i of numbers">
   {{i}}
</p>
<div *ngFor="let number of [].constructor(myCollection)">
    <div>
        Hello World
    </div>
</div>

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

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

由于不带参数的fill()方法(在已接受的答案中提到过)会抛出错误,我建议这样做(对我有用,Angular 7.0.4, Typescript 3.1.6)

<div class="month" *ngFor="let item of items">
...
</div>

在组件代码中:

this.items = Array.from({length: 10}, (v, k) => k + 1);

我认为简单而简短的解决办法就在这里。

你的my.component.ts文件

setArrayFromNumber(i: number) {
  return new Array(i);
}

你的my.component.html文件

<li *ngFor='let in of setArrayFromNumber(5); let i = index'>{{ i }}</li>

就是这样! !