如何使用Angular 2在下拉列表中仅显示唯一值

分享于2023年05月08日 angular drop-down-menu json 问答
【问题标题】:How to display only unique values in the dropdown using Angular 2如何使用Angular 2在下拉列表中仅显示唯一值
【发布时间】:2023-05-07 11:03:01
【问题描述】:

我有一个 JSON 数据,我使用 *ngFor 将“accountNumber”显示到下拉列表中。由于 JSON 数据中有多个条目具有相同的帐号,因此我在下拉列表中多次看到相同的帐号。 enter image description here

html:


json:

`[
{
    "accountNumber": 7890,
    "transactionDate": "4/2/2016",
    "postingDate": "4/3/2016",
    "description": "Pok Pok Thai",
    "category": "Restaurants",
    "amount": 15.00
},
{
    "accountNumber": 7890,
    "transactionDate": "4/3/2016",
    "postingDate": "4/4/2016",
    "description": "Pok Pok Hai",
    "category": "Hotel",
    "amount": 25.00
},

{
    "accountNumber": 8901,
    "transactionDate": "4/6/2016",
    "postingDate": "4/7/2016",
    "description": "Pok Pok Fai",
    "category": "Dairy",
    "amount": 55.00
},
{
    "accountNumber": 8901,
    "transactionDate": "4/7/2016",
    "postingDate": "4/8/2016",
    "description": "Pok Pok Aai",
    "category": "Automotive",
    "amount": 65.00
},

{
    "accountNumber": 4567,
    "transactionDate": "4/9/2016",
    "postingDate": "4/10/2016",
    "description": "Pok Pok Cai",
    "category": "Healthcare",
    "amount": 85.00
},
{
    "accountNumber": 4567,
    "transactionDate": "4/10/2016",
    "postingDate": "4/11/2016",
    "description": "Pok Pok Dai",
    "category": "Healthcare",
    "amount": 95.00
},

{
    "accountNumber": 8901,
    "transactionDate": "4/12/2016",
    "postingDate": "4/13/2016",
    "description": "sit amet",
    "category": "Software",
    "amount": 115.00
}
 ]`

如何避免在下拉列表中显示重复的帐号值?我假设它需要一个自定义管道,但不知道该怎么做。

我是 Angular 2 的新手,并尝试寻找解决方案,但找不到适合我需要的任何东西。


【解决方案1】:

已经发布了带有示例的管道基本解释: How to apply filters to *ngFor

查看适用于您的案例的工作 plunker http://plnkr.co/edit/E7HlWeNJV2N3zwPfI51Q?p=preview .. 我使用了 lodash 库及其 uniqBy 函数,那么管道真的那么简单:

declare var _: any; // lodash, not strictly typed

@Pipe({
    name: 'uniqFilter',
    pure: false
})
@Injectable()
    export class UniquePipe implements PipeTransform {
        transform(items: any[], args: any[]): any {

        // lodash uniqBy function
        return _.uniqBy(items, args);
    }
}

.. 以及组件中的用法:

  • {{ account.accountNumber }}

编辑 :我已将 plunker 更新为最新的 Angular 版本,并在管道中添加了过滤参数。

【讨论】:

  • 我在这一行得到错误 return .uniqBy(items, "accountNumber");错误是 [ts] 找不到名称“ ”。任何我在这里找到的- stackoverflow.com/questions/34660265/… ,在使用之前我们需要导入 lodash 吗?我在 index.html 中像
  • 是的,你需要在使用它之前引用 lodash,但是如果你已经打开了它,那就是在我的 index.html 中的 plunker...尝试在你的 @Pipe 之前添加 declare var _: any; ,我已经更新了答案..
  • 成功了。谢谢@彼得亚当。唯一不同的是,我必须使用“#account of accounts”而不是“let account of accounts”,因为它会引发模板解析错误。
  • 你将如何使用它来获取特定类型的唯一值并通过更改字段名称...使用类似这样的内容...*ngFor="let account of accounts | uniqFilter: 'accountNumber '" ?
  • 我已经用管道参数更新了答案,这是你需要的吗?