Angular get selected datalist object

2020-07-27 02:51发布

This select 1-way binding works

<select [(ngModel)]="selectedLocation">
    <option *ngFor="let location of allLocationNames" [ngValue]="location">{{location.name}}</option>
</select>

selectedLocation will always contain the selected location object.

This datalist 1-way binding does not seem to work

<h4>Guest: <input type="text" name="guest" [(ngModel)]="selectedGuest" list="options">
  <datalist id=options *ngIf="allGuests">
    <option *ngFor="let guest of allGuests" [ngValue]="guest">{{guest.companyName}}</option>
  </datalist>
</h4>

selectedGuest will not contain an object but the string value (guest.companyName) of the selected element.

How can I get the selected object in the datalist example?

标签: angular
3条回答
▲ chillily
2楼-- · 2020-07-27 03:18

The problem is that the input does not have the id attribute. For this to work you need to add the id attribute to the input and the name should be the same as the one of the datalist, please see the solution below:

<h4>Guest:
 <input type="text" id=options name="guest" [(ngModel)]="selectedGuest" list="options">

  <datalist id=options *ngIf="allGuests">
    <option *ngFor="let guest of allGuests" [ngValue]="guest">{{guest.companyName}}</option>
  </datalist>
</h4>
查看更多
可以哭但决不认输i
3楼-- · 2020-07-27 03:19

I found workaround for this problem. You can use the following code :

 <input type="text" list="productList" name="product" [(ngModel)]='currentProduct' (change)="onProductChanged(currentProduct)" />
     <datalist id="productList">
       <select>
        <option *ngFor="let product of products" [value]="product.name"></option>
       </select>
     </datalist>

And in typescript I wrote :

export class MySuperPrivateClass implements OnInit {
currentProduct: string = "";
selectedProduct: Product;

 onProductChanged(productName) {
    console.log(productName);
    this.selectedProduct = this.getSelectedProductByName(productName);
}

 getSelectedProductByName(selectedName: string): Product {
    return this.products.find(product => product.name === selectedName);
}
查看更多
迷人小祖宗
4楼-- · 2020-07-27 03:30

you have to add data attribute to get the object or a property:

<option *ngFor="let guest of allGuests" data-guest="guest" [ngValue]="guest">
      {{guest.companyName}}</option>

and you can getting inside your component:

yourSelectedElement.data('guest')
查看更多
登录 后发表回答