...例如……
<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));
}
}
@OP,你的“不优雅”解决方案已经非常接近了。
如何:
<div class="month" *ngFor="let item of [].constructor(10); let i = index">
...
</div>
这里我从一个空数组中获取Array构造函数:[]。构造函数,因为Array在模板语法中不是一个可识别的符号,而且我懒得像@pardeep-jain在他的第4个例子中那样在组件typescript中执行Array=Array或counter =Array。我调用它时不使用new因为new对于从array构造函数中获取数组来说是不必要的。
Array(30)和new Array(30)是等价的。
数组将为空,但这无关紧要,因为你实际上只是想在循环中使用i from;let i = index。
编辑以回复评论:
问:如何使用变量来设置NgFor循环的长度?
下面是一个关于如何呈现具有可变列/行的表的示例
<table class="symbolTable">
<tr *ngFor="let f of [].constructor(numRows); let r = index">
<td class="gridCell" *ngFor="let col of [].constructor(numCols); let c = index">
{{gridCards[r][c].name}}
</td>
</tr>
</table>
export class AppComponent implements OnInit {
title = 'simbologia';
numSymbols = 4;
numCols = 5;
numRows = 5;
guessCards: SymbolCard[] = [];
gridCards: SymbolCard[][] = [];
ngOnInit(): void {
for (let c = 0; c < this.numCols; c++) {
this.guessCards.push(new SymbolCard());
}
for (let r = 0; r < this.numRows; r++) {
let row: SymbolCard[] = [];
for (let c = 0; c < this.numCols; c++) {
row.push(
new SymbolCard({
name: '' + r + '_' + c
}))
}
this.gridCards.push(row);
}
}
}