角度ng对于故障

问题描述 投票:1回答:2

我有几个月的时间。由于某种原因,角度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

arrays angular
2个回答
1
投票

要按照顺序,请替换:

<div *ngFor="let item of collection | keyvalue; index as i">{{item | json}}</div>

通过:

<div *ngFor="let item of collection">{{item | json}}</div>

3
投票

根据keyvaluedocs的定义。

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

因此,您的密钥(字符串)是默认排序的。

| keyvalue; index as i移除管道*ngFor

© www.soinside.com 2019 - 2024. All rights reserved.