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

后端 未结 2 1187
悲&欢浪女
悲&欢浪女 2020-12-17 00:52

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\'},
         


        
2条回答
  •  生来不讨喜
    2020-12-17 01:39

    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.

    • {{datum.name}}

提交回复
热议问题