[英]How to trigger reactive form valueChanges subscription only on input blur and enter key in Angular 2
[英]How to get selected object from valueChanges but only bind object id to form using Angular reactive forms?
我有一个允许我选择汽车的选择字段,并且汽车 ID 绑定到表单。
<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 => { ... );
我可以更改选择字段以绑定对象而不是像这样的 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>
但随后整个对象都被绑定到表单,而不仅仅是 id,这会弄乱我的表单提交。
有没有一种优雅的方法来获取选定的对象,但仍然只将 id 绑定到表单?
您有 carId,因此只需在 valueChanges 中的汽车数组中查找汽车对象。
更改为 car 值而不是 id 并更改提交逻辑要容易得多。
这有点笨拙,但我找到了一种可以接受的方式。 我将我的选择字段绑定到一个独立的 FormControl,因此通过使用[formControl]=
而不是formControlName=
对其进行的更改不会影响表单
<mat-form-field>
<mat-label>Car</mat-label>
<mat-select [formControl]="car">
<mat-option *ngFor="let car of cars | async" [value]="car">
{{car.carName}}
</mat-option>
</mat-select>
</mat-form-field>
然后我可以订阅更改,对汽车执行我需要的操作,并在表单上设置 carId。
this.car = new FormControl([null, Validators.required]);
this.car.valueChanges.subscribe(selectedCar => {
// Do whatever with selectedCar here
this.form.get('carId').setValue(selectedCar ? selectedCar.carId : null);
});
这有效,但要使其与 Angular Material 错误处理一起工作(因此如果未指定该字段会变为红色),我必须添加一个隐藏的输入绑定到carId
。
<mat-form-field>
<mat-label>Car</mat-label>
<input matInput formControlName="carId" style="display:none">
<mat-select [formControl]="car">
<mat-option></mat-option>
<mat-option *ngFor="let car of cars | async" [value]="car">
{{car.carName}}
</mat-option>
</mat-select>
<mat-error *ngIf="form.get('carId').hasError('required')">
Car is required
</mat-error>
</mat-form-field>
更新我仍然对这个解决方案不满意,因为我还必须确保在调用form.setValue()
时car
选择是同步的,这意味着我必须从它的 id 中查找汽车 - 所以我也可以像亚历山大的回答所说的那样对选择更改进行查找或修改提交逻辑。
我会保留这个答案,以防它对任何人有帮助,但我仍然对其他想法持开放态度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.