值的乘法不适用于输出字段

Multiplication of value not working on output field

我正在尝试使输出字段根据我在输入字段中设置的值乘以它的值。例如。如果输入字段等于 2,则输出字段必须等于 2 * 输出字段的现有值(最初输出字段的值是根据所选货币设置的)。我的代码会更好地解释,我已经创建了一个 stackblitz 来演示它。

这是我的 stckblitz: https://stackblitz.com/edit/angular-9-material-starter-f1drwx?file=src/app/app.component.ts

HTML

<mat-card class="card">    
<mat-form-field class="form-field" appearance="outline">
<mat-label> Input Currency </mat-label>
<input
  matInput
  type="number"
  required
  [(ngModel)]="inputCurrencyValue"
  (keyup)="onUpdate($event)"
  (change)="onUpdate($event)"
/>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-select (selectionChange)="onInputSelectChange($event)" [(ngModel)]="selectedInput" disabled> 
  <mat-option [value]="selectedInput">{{selectedInput[0]}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="form-field" appearance="outline">
<mat-label> Output Currency </mat-label>
<input
  matInput
  type="number"
  disabled
  [(ngModel)]="outputCurrencyValue"
/>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-select (selectionChange)="onOutputSelectChange($event)" [(ngModel)]="selectedOutput">
  <mat-option *ngFor="let item of currenciesArr" [value]="item[1]">{{item[0]}}</mat-option>
</mat-select>
</mat-form-field>
</mat-card>

TS

  public currencies: any;
  public currenciesArr: any;
  inputCurrencyValue: number = 0;
  outputCurrencyValue: number = 0;
  selectedInput = [];
  selectedOutput = [];

  getCurrencies() {
    this.currencies = this.currencyService.currencyRates();
    this.currenciesArr = Object.keys(this.currencies.rates).map((key) => [
      String(key),
      this.currencies.rates[key],
    ]);
    this.selectedInput = this.currenciesArr.find((o) => o[0] === 'EUR');
    this.selectedOutput = this.currenciesArr.find((o) => o[0]);
    console.log(this.selectedOutput);
  }

  onUpdate(event) {
    this.inputCurrencyValue = event.target.value;
  }
  onInputSelectChange(event) {
    this.inputCurrencyValue = event.value;
  }
  onOutputSelectChange(event) {
    this.outputCurrencyValue = event.value;
  }

所以我正在努力的是让输出字段在已经有值之后反映相乘的值。另外,如果货币发生变化,那么我需要显示相乘后的值。

在你的 ts 中添加一个 selectedOutputCurrency 变量来跟踪 selected 输出货币汇率

  selectedOutputCurrency: number = 0;

让您的 select 更新事件处理程序在 select

上设置此货币汇率
  onOutputSelectChange(event) {
    this.selectedOutputCurrency = event.value;
  }

然后在您的输入更改事件处理程序上将输入乘以 selected 货币汇率

  onUpdate(event) {
    this.inputCurrencyValue = event.target.value;

    this.outputCurrencyValue = this.inputCurrencyValue * this.selectedOutputCurrency;
  }

更改输出货币时可以使用类似的逻辑进行反向