首页 > 解决方案 > Angular ngFor 乱序

问题描述

我有几个月的时间。由于某种原因,角度 for 循环不遵循数组的顺序。 这怎么能解决

@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

标签: arraysangular

解决方案


根据文档keyvalue中的定义。

输出数组将按keys 排序。默认情况下,比较器将按 Unicode 点值...

因此,默认情况下您的键(字符串)是有序的。

| keyvalue; index as i您的*ngFor.


推荐阅读