Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angular - In Angular2 *ngFor iteration, how do I output only unique values from the array?

Does it have a built in pipe to do so?

data = [
  {id: 5, name: 'Roger'},
  {id: 5, name: 'Mark'},
  {id: 5, name: 'Zach'},
  {id: 5, name: 'Mark'},
  {id: 5, name: 'Roger'},
];

<ul>
  <li *ngFor="let datum of data">
    {{datum.name}}
  </li>
</ul>

Output

  • Roger
  • Mark
  • Zach
  • Mark
  • Roger

Desired Output

  • Roger
  • Mark
  • Zach
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create your own pipe.

import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash'; 

@Pipe({
  name: 'unique',
  pure: false
})

export class UniquePipe implements PipeTransform {
    transform(value: any): any{
        if(value!== undefined && value!== null){
            return _.uniqBy(value, 'name');
        }
        return value;
    }
}

You need to add in the component the UniquePipe and than add in the HTML file the pipe.

<ul>
  <li *ngFor="let datum of data | unique">
    {{datum.name}}
  </li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...