ng对于完整列表和唯一列表

时间:2018-08-02 21:28:05

标签: angular ngfor

很抱歉,如果这是一个重复的问题,我是Angular的新手,所以我尝试实现了许多无济于事的解决方案,并且似乎找不到能够回答我问题的线程。

我正处于设置Web应用程序的初始阶段,因此现在我正在使用InMemoryDataService(我确实在Laravel中设置了服务,只是还没有绑定它们),如下所示:

import { InMemoryDbService } from 'angular-in-memory-web-api';

export class InMemoryDataService implements InMemoryDbService {
createDb() {
const passwords = [
{ id: 1, team_id: 1, team_name: 'Dragons', fname: 'Bob', lname: 'Smith'},
{ id: 2, team_id: 1, team_name: 'Dragons', fname: 'Jason', lname: 'Roberts'},
{ id: 3, team_id: 1, team_name: 'Dragons', fname: 'Mike', lname: 'Ferraro'},
{ id: 4, team_id: 2, team_name: 'Eagles', fname: 'Jeremy', lname: 'Lovano'},
{ id: 5, team_id: 2, team_name: 'Eagles', fname: 'Robert', lname: 'Casey'},
{ id: 6, team_id: 3, team_name: 'Wolves', fname: 'Mark', lname: 'Thomas'},
{ id: 7, team_id: 3, team_name: 'Wolves', fname: 'Steve', lname: 'Garner'}
];
return {clients};
}
}

我可以使用ngFor很好地显示它并构建数据表,但我也希望仅使用唯一的团队来创建一个选择菜单,如下所示:

<select>
<option value="1">Dragons</option>
<option value="2">Eagles</option>
<option value="3">Wolves</option>
</select>

完成此任务的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

您可以使用lodash库,无论新版本中聋人提供的角度如何

有uniqBy属性可以删除重复项。

例如

let clients = [
    { id: 1, team_id: 1, team_name: 'Dragons', fname: 'Bob', lname: 'Smith'},
    { id: 2, team_id: 1, team_name: 'Dragons', fname: 'Jason', lname: 'Roberts'},
    { id: 3, team_id: 1, team_name: 'Dragons', fname: 'Mike', lname: 'Ferraro'},
    { id: 4, team_id: 2, team_name: 'Eagles', fname: 'Jeremy', lname: 'Lovano'},
    { id: 5, team_id: 2, team_name: 'Eagles', fname: 'Robert', lname: 'Casey'},
    { id: 6, team_id: 3, team_name: 'Wolves', fname: 'Mark', lname: 'Thomas'},
    { id: 7, team_id: 3, team_name: 'Wolves', fname: 'Steve', lname: 'Garner'}
];

clients = _.uniqBy(clients, 'team_name');
console.log(clients);

答案 1 :(得分:1)

您不需要用破折号,并且管道也不是一个好主意(请参见https://angular.io/guide/pipes#no-filter-pipe)。

使用一些现代Javascript只需创建一个唯一元素列表:

this.uniqueTeams = Array.from(new Set(teams.map(team => team.team_name)));

这是类型安全的,没有依赖项,并且没有性能问题。

答案 2 :(得分:0)

您可以执行以下操作:

const clients = [
    { id: 1, team_id: 1, team_name: 'Dragons', fname: 'Bob', lname: 'Smith'},
    { id: 2, team_id: 1, team_name: 'Dragons', fname: 'Jason', lname: 'Roberts'},
    { id: 3, team_id: 1, team_name: 'Dragons', fname: 'Mike', lname: 'Ferraro'},
    { id: 4, team_id: 2, team_name: 'Eagles', fname: 'Jeremy', lname: 'Lovano'},
    { id: 5, team_id: 2, team_name: 'Eagles', fname: 'Robert', lname: 'Casey'},
    { id: 6, team_id: 3, team_name: 'Wolves', fname: 'Mark', lname: 'Thomas'},
    { id: 7, team_id: 3, team_name: 'Wolves', fname: 'Steve', lname: 'Garner'}
];

const uniqueTeams = [];

clients.forEach(client => {
   if(unqiueTeams.indexOf(client.team_name) === -1) {
       uniqueTeams.push(client.team_name);
   }
});

console.log(uniqueTeams);