gpt4 book ai didi

javascript - Angular 响应式(Reactive)形成双向数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 07:03:18 24 4
gpt4 key购买 nike

我正在尝试构建一个 Angular 响应式(Reactive)表单,其中输入字段值根据其他字段中的输入进行更新。三个输入字段 amount , pricetotal应该反射(reflect)更改,以便 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);

stackblitz example modified

关于javascript - Angular 响应式(Reactive)形成双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55367435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com