角获取选定的数据列表对象 [英] Angular get selected datalist object

查看:53
本文介绍了角获取选定的数据列表对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

select 1向绑定有效

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

selectedLocation将始终包含所选位置对象.

selectedLocation will always contain the selected location object.

这种datalist 1向绑定似乎不起作用

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将不包含对象,而是所选元素的字符串值(guest.companyName).

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?

推荐答案

我找到了解决此问题的方法.您可以使用以下代码:

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>

在打字稿中我写了:

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

这篇关于角获取选定的数据列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆