javascript - 如何从 valueChanges 中获取选定的对象,但仅将对象 ID 绑定(bind)到使用 Angular react 形式的形式?

标签 javascript angular angular-reactive-forms

我有一个允许我选择汽车的选择字段,汽车 ID 绑定(bind)到表单。

<mat-form-field>
  <mat-label>Car</mat-label>
  <mat-select formControlName="carId">
    <mat-option *ngFor="let car of cars | async" [value]="car.carId">
      {{car.carName}}
    </mat-option>
  </mat-select>
</mat-form-field>

我想获取汽车的实例,以便我可以从对象中获取其他信息,但我不能使用 valueChanges 来做到这一点,因为它只提供了 id:

this.form.get('carId').valueChanges.subscribe(carId => { ... );

我可以像这样更改选择字段来绑定(bind)对象而不是 id:

<mat-form-field>
  <mat-label>Car</mat-label>
  <mat-select formControlName="carId">
    <mat-option *ngFor="let car of cars | async" [value]="car">
      {{car.carName}}
    </mat-option>
  </mat-select>
</mat-form-field>

但是整个对象都被绑定(bind)到表单,而不仅仅是 id,这会弄乱我的表单提交。

有没有一种优雅的方法来获取选定的对象,但仍然只将 id 绑定(bind)到表单?

最佳答案

您有 carId,因此只需在 valueChanges 的汽车数组中查找汽车对象即可。

虽然更改为汽车值而不是 id 并更改您的提交逻辑要容易得多。

关于javascript - 如何从 valueChanges 中获取选定的对象,但仅将对象 ID 绑定(bind)到使用 Angular react 形式的形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53305690/

相关文章:

html - 在 Angular 8 HTML 模板中为 *ngIf 使用枚举

angular - 在 Angular 中单击 'None of the above option' 时,有没有办法重置复选框项目的其余部分?

使用动态/更新参数的 Angular 7 自定义验证

angular - 如何测试调用服务的 Angular 2 指令?

javascript - D3 过渡。在折线图上使用多条线,并希望在按下按钮时在线之间平滑过渡

javascript - JQuery 相当于 Ruby 的一个 || b

javascript - 是否有一个 javascript 库可以在 stackoverflow 中生成顶部消息功能区?

angular - Protractor .sendKeys() 不适用于 ngModel 的输入

Angular:Formbuilder 中的验证器字母数字或空格

javascript - 按特定顺序对对象数组进行排序