<option *ngFor="let type of UserTypes; let i = index" [ngValue]="type.id">
<span>{{type.name}}</span>
</option>
I want to remove the duplicate data in dropdown option
<option *ngFor="let type of UserTypes; let i = index" [ngValue]="type.id">
<span>{{type.name}}</span>
</option>
I want to remove the duplicate data in dropdown option
You will have to filter the original list (i.e. UserTypes
) before iterating it with *ngFor
, so the first step is to identify how to remove duplicates from this array.
You will need to decide what is considered a duplicate, i.e. which key in the object will be checked for uniqueness. For the purposes of this example I will consider that you have a property name
in your object which needs to be unique. The downstream logic will therefore delete any object which contains a name
value that has already been encountered earlier in the list. There are plenty of examples of how to do this in other SO answers.
Function copied from answer: https://stackoverflow.com/a/56768137/9987590
utils.ts
function getUniqueListBy(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
You could either:
.ts
file, storing it in a new variable (e.g. filteredUserTypes
) and then use that as the subject of your *ngFor
component.ts
ngOnInit() {
// Place this inside your .subscribe() block instead of ngOnInit() if you are fetching data asynchronously/from an API
this.filteredUserTypes = getUniqueListBy(this.UserTypes, 'name')
}
component.html
<option *ngFor="let type of filteredUserTypes" [ngValue]="type.id">
<span>{{type.name}}</span>
</option>
FilterPipe
)pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe<T extends {}> implements PipeTransform {
transform(items: T[], key: keyof T): T[] {
return items.length ? getUniqueListBy(items, key) : []
}
}
component.html
<option *ngFor="let type of UserTypes | filter : 'name'" [ngValue]="type.id">
<span>{{type.name}}</span>
</option>