0

I'm trying to create a search filter to filter results by a certain category. So for instance, take an array of employees, I want to create a select box with each employees department selectable.

I've tried to find tutorials and such on this but despite being what I assume is not an uncommon question, I cannot seem to find any. Below is my current code, though very standard.

<select>
   <option *ngFor="let employee of employees">
      {{employee.Department}}
   </option>
</select>

if i use ngFor in the standard way, I get a select box that renders with the following options:

HR HR HR Management Programming Programming

How do I operate my ngFor in such a way where options that exist already are not added, which is to say, change the select box to have only these options:

HR Management Programming

Liam
  • 11
  • 4
  • can you share your `component.ts` code please? also if you create stackblitz of your problem you will get better response here. – alt255 Aug 19 '19 at 09:17
  • most likely you would need to filter the array in the component/service - take a look at some examples https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – Ric Aug 19 '19 at 09:20
  • I'll create a stack blitz now, but I'm not sure it'll give you any more info than my question. You see, I'm calling from an API so the array isn't explicit (Though for demo purposes I'll declare one and leave my existing code commented) but you can review and judge for yourself of course – Liam Aug 19 '19 at 10:19
  • The issue with filtering unique results is that my array is of Employee objects which are all unique, so filtering the non-unique from the array will return the same array – Liam Aug 19 '19 at 10:21

1 Answers1

0

Just create an array of unique values that you want to display. So every time your this.employees changes, calculate (in your controller) this.departments = [...new Set(this.employees.map(e => e.Department))]; and then loop with ngFor over the departments.

TPReal
  • 1,539
  • 12
  • 26
  • I'm getting a "Property 'map' does not exist for type Object", however this solution feels promising. Do you know what I'm missing? – Liam Aug 19 '19 at 10:25
  • Turns out I made an error when incorporating your solution and with that fixed that solves my issue! Thank you. – Liam Aug 19 '19 at 10:34