当我使用相同的数组时,如何将循环的索引更改回零?
在我的ts文件中
data = [{name: 'A', group: 'one'},{name: 'B', group: 'one'},{name: 'C', group: 'two'},{name: 'D', group: 'two'},{name: 'E', group: 'two'}];
在我的html文件中
<ng-container *ngFor="let apidata of data; let i = index">
<span *ngIf="apidata.group == 'one'">{{apidata.name}} | {{i}}
<ng-container>
<ng-container *ngFor="let apidata of data; let i = index">
<span *ngIf="apidata.group == 'two'">{{apidata.name}} | {{i}}
<ng-container>
我想要显示这样的东西。你可以看到它在传递给新的ng-container
时重置了我的索引<span>A | 1</span>
<span>B | 2</span>
<span>C | 1</span>
<span>D | 2</span>
<span>E | 3</span>
到目前为止,我总是得到这个实际结果
<span>A | 1</span>
<span>B | 2</span>
<span>C | 3</span>
<span>D | 4</span>
<span>E | 5</span>
答案 0 :(得分:0)
只需使用以下逻辑即可解决您的问题
1)组件
中的代码export class AppComponent implements OnInit {
public data = [{name: 'A', group: 'one'},{name: 'C', group: 'two'},{name: 'B', group: 'one'},{name: 'D', group: 'two'},{name: 'E', group: 'two'}];
ngOnInit() {
this.data = this.groupByData(this.data);
}
private groupByData(data): any {
const groups = ['one', 'two'];
return data.sort((item1, item2) => {
if (item1.group === item2.group) {
return 0;
} else if (groups.indexOf(item1.group) < groups.indexOf(item2.group)) {
return -1;
} else {
return 1;
}
});
}
}
2)模板下方
<ng-container *ngFor="let apidata of data; let i = index">
<span>{{apidata.name}} | {{i + 1}}</span>
</ng-container>