我目前正在研究一个ionic2项目。我在数组中获取数据,我必须将其显示为带有侧面字母导航的联系人列表样式。请参考附件。
数据结构有点像这样
[
{"id":1,"first_name":"Harcourt"},
{"id":2,"first_name":"Cart"},
{"id":3,"first_name":"Laina"},
{"id":4,"first_name":"Deborah"},
{"id":5,"first_name":"Kendricks"}
]
我可以使用lodash通过first_name对数组进行排序。但我无法弄清楚如何在angular2中使用* ngFor显示排序数组,以便每次字母更改(从A - > B例如),第一个元素可以被赋予唯一ID,以便在用户点击时侧栏字母表我可以滚动到该元素。
请帮忙。我应该为此创建一些嵌套数组吗?
答案 0 :(得分:2)
您可以尝试这样的事情:
let input = [
{ id: 2, first_name: "Cart" },
{ id: 4, first_name: "Deborah" },
{ id: 6, first_name: "Dobby" },
{ id: 1, first_name: "Harcourt" },
{ id: 5, first_name: "Kendricks" },
{ id: 6, first_name: "Lenny" },
{ id: 3, first_name: "Laina" }
],
people = []
let firstLetter = ""
for(let i in input) {
let currentLetter = input[i].first_name[0].toUpperCase()
if(currentLetter!=firstLetter) {
firstLetter = ""+currentLetter
people.push({ index : firstLetter})
}
people.push(input[i])
}
console.log(people)
然后在模板中,有条件地显示名称或索引:
<li *ngFor="let p of people">
<div *ngIf="p.first_name; else listIndex">
{{p.firstName}}
</div>
<ng-template #listIndex>
<div class="list-index">
{{p.index}}
</div>
</ng-template>
<li>
答案 1 :(得分:0)
链接:
let input = [
{ id: 1, first_name: "Harcourt" },
{ id: 2, first_name: "Cart" },
{ id: 3, first_name: "Laina" },
{ id: 4, first_name: "Deborah" },
{ id: 5, first_name: "Kendricks" },
{ id: 6, first_name: "Dobby" },
{ id: 7, first_name: "Lenny" },
];
input.sort(function(a, b) {
var nameA = a.first_name.toUpperCase();
var nameB = b.first_name.toUpperCase();
if(nameA < nameB) {
return -1;
}
if(nameA > nameB) {
return 1;
}
return 0;
});