...例如……
<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>
?
我无法忍受为组件的简单重复分配数组的想法,所以我写了一个结构指令。在最简单的形式中,这并没有使索引对模板可用,它看起来像这样:
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
这是我试过的最简单的方法
你也可以在你的组件文件中创建一个数组,你可以用*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>
请找到附件我的动态解决方案,如果你想在点击按钮后动态增加数组的大小(这就是我如何得到这个问题)。
必要变量的分配:
array = [1];
arraySize: number;
声明向数组中添加元素的函数:
increaseArrayElement() {
this.arraySize = this.array[this.array.length - 1 ];
this.arraySize += 1;
this.array.push(this.arraySize);
console.log(this.arraySize);
}
在html中调用函数
<button md-button (click)="increaseArrayElement()" >
Add element to array
</button>
使用ngFor迭代数组:
<div *ngFor="let i of array" >
iterateThroughArray: {{ i }}
</div>