角度 - 无法使操作以两种方式工作



我正在使用@HostListener("document:keyup", ["$event"](进行实时操作。 假设我有 3 个输入:A B 和 R(result(。我想对 A+B 求和并在其输入中显示 R。 但是我想修改 R 并让 R 修改 B。

在屏幕上:

输入 A:5

输入 B:3

输入 R:8

然后,手动将 R 修改为 5 更改 B 的值。

输入 R: 8 -> 5. 输入 B 应变为 0。但它永远不会变成 0,因为只要我按下任何按钮,函数就会计算 A+B 并在 R 上给出结果。 如何在不创建循环的情况下实现此目的?

@HostListener("document:keyup", ["$event"])
public operar(){
this.gananciaEuros = 0;
this.gananciaPorcentaje ="";
this.resultado = "";
this.calc.controls.total.setValue(0);
if (!this.calc.controls.costo.value || !this.calc.controls.precioNeto.value) { //si la var está vacía
this.calc.controls.total.setValue("Rellene ambos campos");
}else{
this.resultado = Number(Number(this.calc.controls.precioNeto.value) / Number(this.calc.controls.costo.value));
this.gananciaEuros = Number((Number(this.calc.controls.precioNeto.value) - Number(this.calc.controls.costo.value)).toFixed(2));
this.gananciaPorcentaje = String(((this.resultado - 1) * 100).toFixed(2));
this.calc.controls.total.setValue(Number(this.gananciaEuros)/* +" (" + String(this.gananciaPorcentaje) +"%)" */);
this.calc.controls.precioNeto.setValue(Number(this.gananciaEuros) + Number(this.calc.controls.costo.value))
}
}

.html

<div class="divformulario">
<form [formGroup]="calc">
<div class="formsubconjuntovertical spacebetween">
<div [innerHtml]="'Calcular Ganancia sobre precio' | uppercase | bold" "></div>
<mat-form-field>
<mat-label>Precio costo</mat-label>
<input matInput type="number" formControlName="costo" />
</mat-form-field>
<mat-form-field  >
<mat-label>Precio de venta neto</mat-label>
<input matInput type="number" formControlName="precioNeto" " />
</mat-form-field>
<mat-form-field>
<mat-label>Ganancia</mat-label>
<input matInput type="number" formControlName="total" style="text-align: right;" "/><span matSuffix>€</span>
</mat-form-field>
</div>
</form>
</div>

您可以使用事件keyup并将三个值(a,b,r(绑定到组件变量,而不是使用HostListener

以下是html文件的示例:

A
<input type="number" [(ngModel)]="aValue" (keyup)="changeFromA($event)"/>
B
<input type="number" [(ngModel)]="bValue" (keyup)="changeFromB($event)"/>
R
<input type="number" [(ngModel)]="rValue" (keyup)="changeFromR($event)"/>

在你组件中:

aValue : number = 5;
bValue : number = 3;
rValue : number = 8;
changeFromA(_ : any) {
this.rValue = this.aValue + this.bValue;
}
changeFromB(_ : any) {
this.rValue = this.aValue + this.bValue;
}
changeFromR(_ : any) {
this.bValue = this.rValue - this.aValue;
}

最新更新