...例如……
<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
@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);
}
}
}