我正试图让一个输出字段根据我在输入字段中设置的值乘以它的值。例如,如果输入字段等于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
变量以跟踪所选的输出汇率
selectedOutputCurrency: number = 0;
让您的选择更新事件处理程序在选择上设置此汇率
onOutputSelectChange(event) {
this.selectedOutputCurrency = event.value;
}
在您的输入更改事件处理程序上,将输入乘以所选的汇率
onUpdate(event) {
this.inputCurrencyValue = event.target.value;
this.outputCurrencyValue = this.inputCurrencyValue * this.selectedOutputCurrency;
}
当改变输出货币时,类似的逻辑可以用于反向