SexyMF
SexyMF

Reputation: 11165

Angular ngFor out of order

I have an array of months. for some reason angular for loop does not follow the order of the array. 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

Upvotes: 2

Views: 3356

Answers (2)

According to the definition of keyvalue from the docs.

The output array will be ordered by keys. By default the comparator will be by Unicode point value...

And therefore your keys(string) are ordered by default.

Remove the pipe | keyvalue; index as i from your *ngFor.

Upvotes: 3

veben
veben

Reputation: 22322

To follow the order, replace:

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

by:

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

Upvotes: 1

Related Questions