在Angular2 * ngFor迭代中,如何仅从数组中输出唯一值? [英] In Angular2 *ngFor iteration, how do I output only unique values from the array?

查看:47
本文介绍了在Angular2 * ngFor迭代中,如何仅从数组中输出唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它具有内置管道吗?

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


Output

  • 罗杰
  • 标记
  • 扎克
  • 标记
  • 罗杰

Desired Output

Desired Output

  • 罗杰
  • 标记
  • 扎克

推荐答案

您可以创建自己的管道.

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

您需要在组件中添加UniquePipe,然后在HTML文件中添加管道.

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>

这篇关于在Angular2 * ngFor迭代中,如何仅从数组中输出唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆