Angular Pipe 删除 double

标签 angular pipe

我有一个下拉菜单,其中列出了客户的所有国家/地区代码。目前我遇到的问题是我有很多重复条目,也就是说,如果我有三个来自印度的客户,我的下拉列表将显示 IN, IN , IN 而不是一次。我以为我可以在管道的帮助下解决这个问题,但我不知道如何实现它。

下面是我的管道(它是空的,因为我看不懂代码):

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'duplicates'
})
export class DuplicatesPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    
    return value;


  }

}

这里是我的 html 下拉列表:

  <strong class="ml-2">Country</strong>
     <select class="ml-1" name="countryCode" [(ngModel)]="countryCode" (change)="gender = ''" (change)="activeStatus = ''">
  <option></option>
  <option *ngFor="let customer of customerArray">{{customer.countryCode | duplicates}}</option>
 </select>

最佳答案

您必须将管道应用于您正在迭代的数组。

例如像这样:

@Pipe({ name: "uniqueCountryCodes" })
export class UniqueCountryCodesPipe implements PipeTransform {

  transform(customers: Customer[], args?: any): any { 
    return customers.map(c => c.countryCode).filter((code, currentIndex, allCodes) => allCodes.indexOf(code) === currentIndex);
  }

}

用法:

<option *ngFor="let code of (customerArray | uniqueCountryCodes)">{{ code }}</option>

请记住,只要管道不是 impure ,它只过滤一次,并且在将新客户添加到 customerArray 时不会更新国家/地区代码。

关于Angular Pipe 删除 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795257/

相关文章:

pdf - 检索 pdf 时出现意外的服务器响应 (0)

angular - 通知子组件它是父组件 Angular FormGroup 的一部分

javascript - Angular 2 Aot 错误 : FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

linux - 执行另一个命令输出中给出的行

c - 学习管道、exec、fork,并尝试将三个进程链接在一起

c - read() write() 通过 dup2() 与 stdin 和 stdout 写入 pipe()

node.js - 从 angular2 服务发送正文中的值

javascript - 如何仅缓冲来自可观察源的选定项目集并立即发出其他项目?

angular - 无法让 Angular2 中的 `http.get` 工作

shell - 管道输入到脚本中