首页 > 解决方案 > Angular 绑定 2 选择下拉列表到对象并仅存储选定的值

问题描述

在我的 Angular 组件中,我使用了 2 个 html 选择下拉菜单。型号下拉列表显示上面所选品牌的型号。目前的问题是我想将两者都存储为字符串,但在代码中我从品牌下拉列表中获取整个对象。如果我将ngValue品牌更改为[ngValue]="brand.name",则与模型选择的绑定将不再起作用。目前,选定的汽车品牌正在提交我的表单,存储为品牌对象,车型存储为字符串。

如何选择所选品牌的型号并将品牌存储为字符串?

这是我的代码

<form *ngIf="car" #carEditForm="ngForm" name="form" (ngSubmit)="carEditForm.form.valid 
&& onSubmit()">
    <label for="brand">Car brand</label>
    <select class="form-control" [(ngModel)]="car.brand" name="brand" required>
        <option *ngFor="let brand of brands" [ngValue]="brand">{{ brand.name }}</option>
    </select>
    <label for="model">Model</label>
    <select *ngIf="car.brand" [(ngModel)]="car.model" class="form-control" name="model" 
     required>
        <option *ngFor="let model of car.brand.models" value="{{ model }}">
            {{ model }} 
        </option>
    </select>
    ...
</form>

和课程:

export class Car {
  key: string
  brand: string
  model: string
}

export class Brand {
  key: string
  name: string
  models: []
}

编辑:评论中的解决方案

标签: htmlangulartypescript

解决方案


推荐阅读