I have drop down menu that lists all the country codes of the customer. At the moment I have the problem that I have a lot of double entries, that is if I have three customers from India my dropdown will show IN, IN , IN instead of just one time. I thought I could fix this with the help of a pipe but am blanking how to implement it.
below is my pipe (which is empty because I can't figure out the code):
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'duplicates'
})
export class DuplicatesPipe implements PipeTransform {
transform(value: any, args?: any): any {
return value;
}
}
and here my html drop down:
<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>
you must apply the pipe to the array you are iterating over.
e.g. something like this:
@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);
}
}
usage:
<option *ngFor="let code of (customerArray | uniqueCountryCodes)">{{ code }}</option>
keep im mind that as long the pipe is not impure, it filters only once and won't update the countrycodes when a new customer is added to the customerArray.
You don't need pipe here, you can just remove duplicates from the customerArray itself before binding.
let filteredCustomerArray = [];
this.customerArray.filter(cust=>filteredCustomerArray.indexOf(cust.countryCode) === -1 &&
filteredCustomerArray.push(cust.countryCode));
now do ngFor over this array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With