...例如……

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

?


当前回答

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

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

其他回答

我无法忍受为组件的简单重复分配数组的想法,所以我写了一个结构指令。在最简单的形式中,这并没有使索引对模板可用,它看起来像这样:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[biRepeat]' })
export class RepeatDirective {

  constructor( private templateRef: TemplateRef<any>,
             private viewContainer: ViewContainerRef) { }

  @Input('biRepeat') set count(c:number) {
    this.viewContainer.clear();
    for(var i=0;i<c;i++) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}

http://plnkr.co/edit/bzoNuL7w5Ub0H5MdYyFR?p=preview

使用自定义结构指令索引:

根据Angular文档:

createEmbeddedView Instantiates an embedded view and inserts it into this container. abstract createEmbeddedView(templateRef: TemplateRef, context?: C, index?: number): EmbeddedViewRef. Param Type Description templateRef TemplateRef the HTML template that defines the view. context C optional. Default is undefined. index number the 0-based index at which to insert the new view into this container. If not specified, appends the new view as the last entry.

当angular通过调用createEmbeddedView创建模板时,它也可以传递将在ng-template中使用的上下文。

使用context可选参数,你可以在组件中使用它, 在模板中提取它,就像你使用*ngFor一样。

app.component.html:

<p *for="number; let i=index; let c=length; let f=first; let l=last; let e=even; let o=odd">
  item : {{i}} / {{c}}
  <b>
    {{f ? "First,": ""}}
    {{l? "Last,": ""}}
    {{e? "Even." : ""}}
    {{o? "Odd." : ""}}
  </b>
</p>

for.directive.ts:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

class Context {
  constructor(public index: number, public length: number) { }
  get even(): boolean { return this.index % 2 === 0; }
  get odd(): boolean { return this.index % 2 === 1; }
  get first(): boolean { return this.index === 0; }
  get last(): boolean { return this.index === this.length - 1; }
}

@Directive({
  selector: '[for]'
})
export class ForDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }

  @Input('for') set loop(num: number) {
    for (var i = 0; i < num; i++)
      this.viewContainer.createEmbeddedView(this.templateRef, new Context(i, num));
  }
}

NgFor还没有使用数字代替集合的方法, 目前,*ngFor只接受一个集合作为参数,但你可以通过以下方法做到这一点:

使用管

demo-number.pipe.ts:

import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
  transform(value, args:string[]) : any {
    let res = [];
    for (let i = 0; i < value; i++) {
        res.push(i);
      }
      return res;
  }
}

对于新版本,你必须改变你的导入并删除args[]参数:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
  transform(value) : any {
    let res = [];
    for (let i = 0; i < value; i++) {
        res.push(i);
      }
      return res;
  }
}

html:

<ul>
  <li>Method First Using PIPE</li>
  <li *ngFor='let key of 5 | demoNumber'>
    {{key}}
  </li>
</ul>

直接在HTML(视图)中使用数字数组

<ul>
  <li>Method Second</li>
  <li *ngFor='let key of  [1,2]'>
    {{key}}
  </li>
</ul>

使用Split方法

<ul>
  <li>Method Third</li>
  <li *ngFor='let loop2 of "0123".split("")'>{{loop2}}</li>
</ul>

使用在组件中创建新数组

<ul>
  <li>Method Fourth</li>
  <li *ngFor='let loop3 of counter(5) ;let i= index'>{{i}}</li>
</ul>

export class AppComponent {
  demoNumber = 5 ;
  
  counter = Array;
  
  numberReturn(length){
    return new Array(length);
  }
}

#演示工作

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

由于不带参数的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);