首页 > 解决方案 > Angular 反应式形成双向数据绑定

问题描述

我正在尝试构建一个 Angular 反应式表单,其中输入字段值根据其他字段中的输入进行更新。三个输入字段amountprice并且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);
  }
}

标签: javascriptangular

解决方案


this.orderForm.value是只读的。那么你可以尝试做这样的事情

this.orderForm.controls['total'].setValue(price/ this.orderForm.value.amount);

修改了 stackblitz 示例


推荐阅读