Angular how to distinguish elements with the same value in a html datalist

Viewed 32

basically my boss is forcing me to use a datalist in an interface for our website to select an employee from the list of all the employees even though there's no telling wheter the user used the keyboard to type whatever he wants or he actually picked from the list. trouble is the list must only show the full name, ad once the form is submitted I need the id of the employee not his damn name, I could just use the name of the guy to find his id, but if there are more than one employee with th same name it won't work. Now I know it will probably never happen.. but my boss wants me to fix it. No I can't use anything other than a datalist, as stupid as a choice it is it wasn't mine to make so don't even suggest it. Here's the code:

<input list="empl-list" type="text">                                   
<datalist id="empl-list">
<option *ngFor="let empl of employees" value="{{empl.name + ' ' + empl.surname}}">
</datalist>

I figured if I binded a function to the click event on the option of the datalist I could pass it the empl and access his id, but apparently there is no click event on datalists. I could scan the list and add a counter at the end of the surname ("Jim William", "Jim William 2"...) but I don't know if my boss would accept it and I myself would rather use another solution if possible. Any suggestions?

1 Answers

It's a bit "bizarro", but you can use a variable and ngModel in the way

  flavor:any;
  options=[
    {value:0,text:"Chocolate"},
    {value:1,text:"Coconut"},
    {value:2,text:"Mint"},
    {value:3,text:"Strawberry"},
    {value:4,text:"Vanilla"}
  ]
  findName(flavor) {
    if (!flavor) return '';
    const option = this.options.find((x) => x.value == flavor);
    return option ? option.text : flavor;
  }



<label for="ice-cream-choice">Choose a flavor:</label>
<input  [ngModel]="findName(flavor)" (ngModelChange)="flavor=$event"  list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />

<datalist id="ice-cream-flavors">
    <option *ngFor="let option of options" [value]="option.value">
         {{option.text}}
    </option>
</datalist>
Flavor: {{flavor}}

See that the variable "flavor" get the value of the option selected

a stackblitz

Related