我有一个允许我选择汽车的选择字段,汽车 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/