角管去除双打

kon*_*ban 4 pipe angular

我有下拉菜单,列出了客户的所有国家/地区代码。目前我遇到的问题是我有很多重复输入,也就是说,如果我有来自印度的三个客户,我的下拉列表将显示 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;


  }

}
Run Code Online (Sandbox Code Playgroud)

这里是我的 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>
Run Code Online (Sandbox Code Playgroud)

A.W*_*nen 5

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

例如这样的事情:

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

}
Run Code Online (Sandbox Code Playgroud)

用法:

<option *ngFor="let code of (customerArray | uniqueCountryCodes)">{{ code }}</option>
Run Code Online (Sandbox Code Playgroud)

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