html - 键入时打印文本字段值的计算结果
问题描述
我有 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 "/>
解决方案
您将数据绑定与响应式表单相结合。H1 绑定到组件上的两个公共属性,分别称为价格和折扣。
输入使用两个 formControl 实例,一个称为 price,另一个称为 discount。据推测,在 H1 上方的某个地方,您有一个外部级别元素,例如带有 [formGroup]="myFormGroup" 绑定的 div。myFormGroup 也将是组件的属性(并且将具有价格控制和折扣控制)。
无论如何,要让它工作,要么:
- 为 price 定义一个公共只读属性,以及另一个称为 discount 的属性,它们从 formGroup 中获取它们的值:
public get price(): number {
return this.myFormGroup.controls.price.value;
}
public get discount(): number {
return this.myFormGroup.controls.discount.value;
}
- 定义价格和折扣的读/写公共属性,并在表单控件值更改时写入它们:
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
推荐阅读
- github - Terraform 的 .Gitignore 文件
- react-native - 如何将 XML 中的字符串写入 React Native 中的变量?
- c++ - C++ 无序集
返回值 - javascript - 我正在学习使用 React Router,但我无法理解这种行为
- python - 如何编写导入配置文件?
- c# - 当我向 ASP.NET CORE 中的 Web API 控制器发送多部分请求时,使用哪种格式化程序?
- javascript - Antd 行选择显示在第二列
- dpkg - `dpkg-query -S` 的实现在 C 中真的有必要吗?
- javascript - express.js 应用程序的 EJS 模板:将数据传输到变量中
- c# - 尝试调用接口服务时抛出控制器错误“非静态字段需要对象引用”