Angular - 从 HTML select 获取项目 ID 和值

Angular - Getting item id and value from a HTML select

我正在使用 Angular 和 AngularFire 从 Firestore 获取客户端列表。我已将它们显示在 HTML 下拉列表中 (select)。

在 select 购买一件商品后,我想获得 client.idclient.name

到目前为止,这能够让我在 selection 上获得客户端 ID。我还想从下拉列表中 selecting 一个项目是 client.name.

<select [(ngModel)]="selectedClient">
   <option *ngFor="let client of clients | async" [value]="client.id"> 
        {{ client.name}} 
   </option>
</select>

您可以传入整个对象而不仅仅是 ID。

<select [(ngModel)]="selectedClient">
   <option *ngFor="let client of clients | async" [ngValue]="client"> 
        {{ client.name}} 
   </option>
</select>

那么您将可以访问两个属性,client.idclient.name

只需在选项值中传递 client 而不是 client.id

在您的 HTML 文件中

<select (change)="selectedClient($event.target.value)">
   <option *ngFor="let client of clients | async" [value]="client"> 
        {{ client.name}} 
   </option>
</select>

在你的ts文件中

selectedClient(client){
   console.log(client.id+" "client.name); 
   //here u can access client id and client name and you can do any operations required
}

您可以将对象作为值传递,但在这种情况下使用 ngValue 而不是 value 属性,因为 value 只接受字符串。

<select [(ngModel)]="selectedClient">
   <option *ngFor="let client of clients | async" [ngValue]="client">
   <!------------------------------------here-----^^^^^^^^^^^^^^^^^-> 
        {{ client.name}} 
   </option>
</select>