javascript - Angular 反应式形成双向数据绑定
问题描述
我正在尝试构建一个 Angular 反应式表单,其中输入字段值根据其他字段中的输入进行更新。三个输入字段amount
,price
并且total
应该反映更改以便amount * price = total
成立。完整代码https://stackblitz.com/edit/angular-e7rnxf
import {
Component,
Input
} from '@angular/core';
import {
FormBuilder
} from '@angular/forms';
@Component({
selector: 'hello',
template: `
<form [formGroup]="orderForm" (ngSubmit)="onSubmit()">
Amount: <input (keyup)="onAmountChange($event)" formControlName="amount">{{ orderForm.value.amount }}<br>
Price: <input (keyup)="onPriceChange($event)" formControlName="price">{{ orderForm.value.price }}<br>
Total: <input (keyup)="onTotalChange($event)" formControlName="total"> {{ orderForm.value.total }}<br>
<button type="submit">Submit</button>
</form>
`
})
export class HelloComponent {
constructor(private fb: FormBuilder) {}
orderForm = this.fb.group({
amount: 200,
price: 95,
total: ''
});
onTotalChange(e) {
const total = e.currentTarget.value;
this.orderForm.value.amount = total / this.orderForm.value.price;
}
onAmountChange(e) {
const amount = e.currentTarget.value;
this.orderForm.value.total = this.orderForm.value.amount * this.orderForm.value.price;
}
onPriceChange(e) {
const price = e.currentTarget.value;
this.orderForm.value.total = price * this.orderForm.value.amount;
}
onSubmit() {
console.log(this.orderForm.value);
}
}
解决方案
this.orderForm.value
是只读的。那么你可以尝试做这样的事情
this.orderForm.controls['total'].setValue(price/ this.orderForm.value.amount);
推荐阅读
- plugins - 您可以访问十一(11ty)插件中的页面前端(或其他数据)吗
- google-cloud-platform - scp 从 GCP 虚拟机内部到另一台服务器
- axios - Laravel 8 验证“必需”与文档不一致
- python - 按 form_id 分隔行
- reactjs - 我的代码有什么问题?任何人都可以帮助我吗
- java - 如何将此方法从使用 java.io.File 转换为 java.nio.file?
- asp.net-core - 在 Blazor 中将值从父级转移到子级 onclick
- c - 让迷宫算法在开放迷宫上工作
- python - 如何根据多个条件替换 2 个数据框列中的值?
- html - html如何为表格中的表格保留表格列