Angular get selected datalist object

2020-07-27 02:33发布

问题:

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?

回答1:

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);
}


回答2:

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')


回答3:

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>


标签: angular