...例如……
<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>
?
使用自定义结构指令索引:
根据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));
}
}
我用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为负会发生什么)。
在你的组件中,你可以定义一个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 {
(...)
}