I am trying to make an output field multiply it's value based on a value I set in my input field. eg. if the input field is equal to 2 then the output field must equal to 2 * the existing value the output field(Initially output field has a value that is set based on the currency that is chosen). My code will explain better and I have created a stackblitz to demo it.
Here is my stckblitz: https://stackblitz.com/edit/angular-9-material-starter-f1drwx?file=src/app/app.component.ts
HTML
<mat-card >
<mat-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 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;
}
So what I am struggling with is to make the output field reflect the multiplied values after it already has a value. Also if the currency is changed then I need to show the multiplied value.
CodePudding user response:
In your ts Add a selectedOutputCurrency
variable to keep track of the selected output currency rate
selectedOutputCurrency: number = 0;
Have your select update event handler set this currency rate on select
onOutputSelectChange(event) {
this.selectedOutputCurrency = event.value;
}
And on your input change event handler multiply the input by the selected currency rate
onUpdate(event) {
this.inputCurrencyValue = event.target.value;
this.outputCurrencyValue = this.inputCurrencyValue * this.selectedOutputCurrency;
}
Similar logic can be used for the reverse when changing the output currency