...例如……

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

?


当前回答

你也可以用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>

其他回答

我用Angular 5.2.6和TypeScript 2.6.2解决了这个问题:

class Range implements Iterable<number> {
    constructor(
        public readonly low: number,
        public readonly high: number,
        public readonly step: number = 1
    ) {
    }

    *[Symbol.iterator]() {
        for (let x = this.low; x <= this.high; x += this.step) {
            yield x;
        }
    }
}

function range(low: number, high: number) {
    return new Range(low, high);
}

它可以像这样在组件中使用:

@Component({
    template: `<div *ngFor="let i of r">{{ i }}</div>`
})
class RangeTestComponent {
    public r = range(10, 20);
}

为了简洁,故意省略错误检查和断言(例如,如果step为负会发生什么)。

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

你也可以在你的组件文件中创建一个数组,你可以用*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>

使用管道将数字转换为数组。

@Pipe({
  name: 'enumerate',
})
export class EnumeratePipe implements PipeTransform {
  transform(n: number): number[] {
    return [...Array(n)].map((_,i) => i);
  }
}

然后在模板中使用管道。

<p *ngFor="let i of 5 | enumerate">
   Index: {{ i }}
</p>

https://stackblitz.com/edit/angular-ivy-pkwvyw?file=src/app/app.component.html

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

在.ts:

max = 10;    

. html:

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

你可以使用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);
}

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