How to display only unique values in the dropdown using Angular 2

后端 未结 1 375
独厮守ぢ
独厮守ぢ 2021-01-14 19:55

I have a JSON data from which I am displaying \'accountNumber\' into a dropdown using *ngFor. Since there are multiple entries in JSON data with the same account number, I a

相关标签:
1条回答
  • 2021-01-14 20:25

    There is already post explaing basic of pipes with examples: How to apply filters to *ngFor

    See the working plunker for your case http://plnkr.co/edit/E7HlWeNJV2N3zwPfI51Q?p=preview .. I have used lodash library and its uniqBy function, then the pipe is really that simple:

    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);
        }
    }
    

    .. and the usage in your component:

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

    EDIT: I've updated the plunker to latest Angular version, and added filtering parameter to the pipe.

    0 讨论(0)
提交回复
热议问题