首页 > 解决方案 > 键入时打印文本字段值的计算结果

问题描述

我有 2 个接受价格和折扣的文本框。当我在这些文本框中输入值时,我需要计算折扣后的价格并打印出来。

但是,折扣后的价格不会显示。有人能帮助我吗。

 <h1> Price after discount is  {{price/discount * 100}} % </h1>

 <input type="number" name" class="form-control" aria-label="price " pattern="[0-9]"
               [disabled]="true" name="price "  formControlName="price "/>

 <input type="number" name" class="form-control" aria-label="discount " pattern="[0-9]"
               [disabled]="true" name="discount "  formControlName="discount "/>

标签: htmlangulartypescript

解决方案


您将数据绑定与响应式表单相结合。H1 绑定到组件上的两个公共属性,分别称为价格和折扣。

输入使用两个 formControl 实例,一个称为 price,另一个称为 discount。据推测,在 H1 上方的某个地方,您有一个外部级别元素,例如带有 [formGroup]="myFormGroup" 绑定的 div。myFormGroup 也将是组件的属性(并且将具有价格控制和折扣控制)。

无论如何,要让它工作,要么:

  1. 为 price 定义一个公共只读属性,以及另一个称为 discount 的属性,它们从 formGroup 中获取它们的值:

public get price(): number {
  return this.myFormGroup.controls.price.value; 
}

public get discount(): number {
  return this.myFormGroup.controls.discount.value;
}

  1. 定义价格和折扣的读/写公共属性,并在表单控件值更改时写入它们:

public price: number;
public discount: number;
private priceChangedSubsription: Subscription;
private discountChangedSubscription: Subscription;

public myFormGroup: FormGroup = new FormGroup({
  price: new FormControl(0),
  discount: newFormControl(0),
});

// Remember to implement NgOnDestroy, and unsubscibe from this observable there 
this.priceChangedSubscription = this.myFormGroup.controls.price.valueChange.subscribe(val => {
  this.price = val;
});

// Do the same for discount changes


推荐阅读