0

In my html I have this piece of code

Html...

<input type="text" list="select" [(ngModel)]="appSelect" (change)="picked($event.target.value)" />
<datalist id="select">
<option selected="" value="">Select...</option>
<option *ngFor="let i of app; let x = index" [value]="i.info" >{{i.name}}</option>
</datalist>

Component...

appSelect: any;
      picked(value: any) {
        console.log (value); 
      }

above prints what I want but the dropdown shows 2 values. With i.info on the left and i.name on the right in the dropdown column.

  Dropdown:  [i.info         i.name]

I wanted to show only the i.name in the dropdown column

  Dropdown:  [i.name]

Now...I have tried a different approach.

Html....

<input type="text" list="select" [(ngModel)]="selectedVal" (ngModelChange)="picked($event)" />
<datalist id="select">
<option selected="" value="">Select...</option>
<option *ngFor="let i of app; let x = index" [ngValue]="i" >{{i.name}}</option>
</datalist>

@Input() selectedVal: string;
      picked(value: any) {
        console.log (value); 
      }

Above shows correct value in the dropdown

   Dropdown: [i.name]

But the issue is that the value passed to picked is [i.name] and not [i.info] So how do I get the info passed in while show the name only in the dropdown display?

logger
  • 1,983
  • 5
  • 31
  • 57

1 Answers1

1

Probably not the best solution, but it works. U can use the javascript find method to search the array and return the correct object like this:

  app = [
    { name: 'Dominos', info: 'pizza'},
    { name: 'Taco Bell', info: 'tacos'},
    { name: 'McDonalds', info: 'hamburgers'}
  ]
  selectedValName: string;
  selectedValInfo: string;
  picked(value: any) {
    this.selectedValInfo = this.app.find(obj => obj.name == value).info
    console.log(this.selectedValInfo);
  }

see stackblitz demo

Engam
  • 1,051
  • 8
  • 17
  • this worked. thanks you. I was wonder why in the selection it would display twice? why does [value] shows as part of dropdown display? – logger Sep 28 '18 at 16:04
  • @logger - You may find answers in [this question](https://stackoverflow.com/q/29882361/1009922). – ConnorsFan Sep 28 '18 at 16:08