1

I have a dropdown with various currency types. I want to display all the currencies rates into selected currency type rates all over the page. After a research, I found this can be solved by creating custom pipe in angular. How this can be done?

I already created custom pipe but under transform function how I can into covert the selected currency type.

<form>
            <div class="form-group pt-2 display-inline">
                <select class="form-control w-200 display-inline" [(ngModel)]="dataService.selectedCurrency" (change)="currencySelected($event)">
                  <option disabled>Select Currency</option>
                  <option *ngFor="let item of _dataList.Currency" value="{{item.key}}">
                    {{item.value}}
                  </option>
                </select>
              </div>
            </form>

The currency should be converted into the selected currency type and respective rate should be changed to all over page.

divya dave
  • 471
  • 1
  • 9
  • 28
  • 1
    Possible duplicate of [Pass multiple values to pipe in Angular 6](https://stackoverflow.com/questions/53555003/pass-multiple-values-to-pipe-in-angular-6) – mbojko Oct 16 '19 at 10:47
  • You probably need to pass the dataService.selectedCurrency to the custom pipe you crate and use this pipe anywhere you want – noririco Oct 16 '19 at 10:48

1 Answers1

0

If you want to change currency when it is selected in dropDown, then create a variable and apply it in your currency:

TypeScript:

selectedCurrency = 'USD';
printedOption: string;

options = [
    { name: "USD", value: 1, currencyRate: 25 },
    { name: "CAD", value: 2, currencyRate: 15 },
    { name: "CLP", value: 3, currencyRate: 35 }
]

convertWithCurrencyRate(value: number, currency: string){
    let currencyRate = this.options.find(f=> f.name === currency).currencyRate;
    if (currencyRate) {
        return value * currencyRate;
    }

    return value;
}

HTML:

<select 
    class="form-control w-200 display-inline" 
    [(ngModel)]="selectedCurrency" 
    (change)="currencySelected($event)">
    <option disabled>Select Currency</option>
    <option *ngFor="let item of _dataList.Currency" value="{{item.key}}">
         {{item.value}}
    </option>
</select>

<div class="price">{{  convertWithCurrencyRate(555, selectedCurrency) 
                           | currency:selectedCurrency:true:'3.2-2'  }}</div>

An example at the stackblitz.

StepUp
  • 36,391
  • 15
  • 88
  • 148