Home > OS >  how do I get my data from datalist to appear in the input field
how do I get my data from datalist to appear in the input field

Time:05-21

  <li >
    <div >
      <label for="funNumber">fun Number</label>
      <input type="text"  id="funId" maxlength="6" formControlName="funId" list="funNumberList" />
      <datalist id="funNumberList">
        <option value="{{item.id}}" *ngFor="let item of funNumberList">{{item.friendlyName}}</option>
      </datalist>
    </div>
  </li>

When the user selects an item from datalist, the input is updated with the 'value'. I want the input to display the item.friendlyName

See the image. It shows

10

AC-03

I want to display AC-03 instead of 10

enter image description here

CodePudding user response:

  <select name="names" id="myNames">
    <option *ngFor="let user of users" value="name">{{ user.firstName }}</option>
  </select>

enter image description here

I recreated a fast random array, and it is working fine for me.

CodePudding user response:

public codeList = [
    { id: 1, name: 'Angular 2 ' },
    { id: 2, name: 'Angular 4' },
    { id: 3, name: 'Angular 5' },
    { id: 4, name: 'Angular 6' },
    { id: 5, name: 'Angular 7' },
    { id: 5, name: 'Angular 8' },
    { id: 5, name: 'Angular 9' },
    { id: 5, name: 'Angular 11' },
    { id: 5, name: 'Angular 12' },
  ];

  public saveCode(e): void {
    let find = this.codeList.find(x => x?.name === e.target.value);
    console.log(find?.id);
  }
<input type="text" list="codes" [(ngModel)]="codeValue" (change)="saveCode($event)">
<datalist id="codes">
  <option *ngFor="let c of codeList" [value]="c.name" >{{c.name}}</option>
</datalist>

CodePudding user response:

If friendlyName is unuqie

<li >
  <div >
  <label for="funNumber">fun Number</label>
  <input type="text"  list="list" (change)="getId($event)" />
  <datalist id="list">
    <option #item value="{{ item.friendlyName }}" *ngFor="let item of list">
      {{ item.id }}
    </option>
  </datalist>
</div>
list = [
   { id: 1, friendlyName: 'a' },
   { id: 2, friendlyName: 'b' },
   { id: 3, friendlyName: 'c' },
];

getId(ev: Event) {
  const fn = (ev.target as HTMLInputElement)?.value;
  console.log('name', fn);

  const id = this.list.filter((item) => item.friendlyName == fn.toString())[0].id;
  console.log('id',id);
}
  • Related