【问题标题】:Angular - Getting item id and value from a HTML selectAngular - 从 HTML 选择中获取项目 ID 和值
【发布时间】:2019-08-25 23:01:48
【问题描述】:

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

选择一个项目后我想获得client.idclient.name

到目前为止,这可以让我在选择时获得客户 ID。从下拉列表中选择项目时,我还想得到client.name

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

【问题讨论】:

标签: angular google-cloud-firestore html-select


【解决方案1】:

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

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

然后您将可以访问client.idclient.name 这两个属性。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 虽然此上下文可能会回答问题,但提供有关它如何和/或为什么解决问题的其他上下文将提高​​答案的长期价值。
    【解决方案3】:

    在您的 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
    }
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 哇,不知道你能做到。我将如何访问 .ts 文件中该对象的项目。例如....console.log(this.selectedClient.client)(这显然行不通,但希望能突出我的观点)
      • @Que 在 ts 文件中你可以像 this.selectedClient.namethis.selectedClient.id 一样得到它
      • 这就是我的想法,但是,在尝试控制台注销时,会出现以下错误Property 'id' does not exist on type 'object'。有什么想法吗?
      • @Que : 检查console.log(this.selectedClient)
      • 啊,是:any而不是对象。非常感谢伙计。非常感谢。
      猜你喜欢
      • 2022-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2020-03-23
      • 2018-03-08
      • 2021-11-26
      • 2013-06-12
      相关资源
      最近更新 更多