【问题标题】:Getting the Selected Object in Select Option in Angular在 Angular 的 Select 选项中获取选定对象
【发布时间】:2018-03-14 04:36:04
【问题描述】:

我有这个对象数组,我放在选择选项中,我想在选择选项中选择一个对象列表。但是我无法获得该对象列表的值。它输出[对象] [对象]。我想获得该公司对象的选定列表。我将它分配给 [value],它得到 [object][Object]。

<div class="select" >
    <select class="form-control col-lg-8" #selectedValue (change)="assignCorporationToManage(selectedValue.value)">
        <option *ngFor="let corporation of user_corporations" [value]="corporation">{{corporation.corp_name}}</option>    
    </select>
</div>

ts

assignCorporationToManage(selectedValue) {
     console.log(selectedValue)
}

【问题讨论】:

    标签: arrays angular javascript-objects angular-services


    【解决方案1】:

    试试这样:

    为您的选择添加 ngModel 并使用 ngModelChange 而不是更改。

    1. 添加 ngModel
    2. 使用 ngModelChange 而不是 change。
    3. 使用 [ngValue] 而不是 [value]。

    component.html

    <select class="form-control col-lg-8" #selectedValue name="selectedValue" id="selectedValue" [(ngModel)]="selectedValue" (ngModelChange)="assignCorporationToManage($event)">
        <option *ngFor="let corporation of user_corporations" [ngValue]="corporation">{{corporation.corp_name}}</option>
    </select>
    

    组件.ts

    assignCorporationToManage(selectedValue) {
         console.log(selectedValue)
    }
    

    【讨论】:

    • 改成这个[(ngModel)]="selectedValue[i]"
    【解决方案2】:

    您可以使用 selectedValue 从列表中获取该特定对象。

    <select class="form-control col-lg-8" #selectedValue name="selectedValue" id="selectedValue" [(ngModel)]="selectedValue">
        <option *ngFor="let corporation of user_corporations" [ngValue]="corporation">{{corporation.corp_name}}</option>
    </select>
    

    在你的 ts 或 js 文件中,

    const selectedObject = this.user_corporations.find((el: any) => {
      return el?.corporation == this.selectedValue;
    });
    

    之后,您可以随意使用selectedObject

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 2022-10-13
      • 2018-08-08
      • 1970-01-01
      • 2019-11-30
      相关资源
      最近更新 更多