我有几个月的时间。由于某种原因,角度for循环不遵循数组的顺序。 How can that be fixed?
@Component({
selector: 'my-app',
template: `<div *ngFor="let item of collection | keyvalue; index as i">{{item | json}}</div>`,
})
export class AppComponent {
collection : {key : any, value : any}[] = [];
constructor(){
let i = 0;
for(let month of moment().locale('en-US').localeData().monthsShort()){
i++;
this.collection.push({key : i,value : month});
}
}
https://stackblitz.com/edit/angular-i25npn?file=src%2Fapp%2Fapp.component.ts
要按照顺序,请替换:
<div *ngFor="let item of collection | keyvalue; index as i">{{item | json}}</div>
通过:
<div *ngFor="let item of collection">{{item | json}}</div>
根据keyvalue
的docs的定义。
输出数组将按键排序。默认情况下,比较器将按Unicode点值...
因此,您的密钥(字符串)是默认排序的。
从| keyvalue; index as i
移除管道*ngFor
。