如何使用Angular 2

时间:2016-07-13 21:31:47

标签: json drop-down-menu angular

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

HTML:

<div class="btn btn-default dropdown-toggle" type="button" 
  id="dropdownMenu" data-toggle="dropdown" aria-expanded="true">

  <span>Select</span>
  <span class="caret"></span>
  <ul class="select-menu" aria-labelledby="dropdownMenu">
    <li *ngFor="#account of accounts">{{account.accountNumber}}</li>
  </ul>
</div>

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 个答案:

答案 0 :(得分:1)

已经用例子How to apply filters to *ngFor

解释了管道的基本原理

查看您的案例http://plnkr.co/edit/E7HlWeNJV2N3zwPfI51Q?p=preview的工作plunker ..我使用了 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);
    }
}

..以及组件中的用法:

<div>
    <ul>
        <li *ngFor="let account of accounts | uniqFilter: 'accountNumber'">{{ account.accountNumber }}</li>
    </ul>
</div>

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