[英]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. 由于某种原因,角度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 https://stackblitz.com/edit/angular-i25npn?file=src%2Fapp%2Fapp.component.ts
According to the definition of keyvalue
from the docs . 根据docs中keyvalue
的定义。
The output array will be ordered by keys . 输出数组将按键排序 。 By default the comparator will be by Unicode point value... 默认情况下,比较器将使用Unicode点值...
And therefore your keys(string) are ordered by default. 因此,默认情况下您的键(字符串)是有序的。
Remove the pipe | keyvalue; index as i
疏通管道| keyvalue; index as i
| keyvalue; index as i
| keyvalue; index as i
from your *ngFor
. 从您的*ngFor
| keyvalue; index as i
。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.