Vipin
Vipin

Reputation: 41

How to set currency format of input value in angular Reactive Form?

I want to apply currency format in my amount field when user move to the another field then amount value will transform into currency format and when control focused then currency format will be removed.

I have tried with hostlistner to bind the event onblur and onfocus event in custom directive, But I want without creating custom directive?

This is my HTML code.

<input type="text" formControlName="amount" />
On the amount field I want to set currency format without creating custom directive.

Is it possible without creating custom directive?

Upvotes: 4

Views: 12248

Answers (2)

Edward Abattam
Edward Abattam

Reputation: 91

Might not necessarily be what you want but might be useful to someone else. You could try toggling between two inputs.

<input type="text" id="amount" formControlName="amount"(blur)="hideAmountInput()">

<input type="text" id="hidden-amount" (focus)="showAmountInput()"
 style="display: none;" [value]="form.controls['amount'].value | currency:'$' " >
 hideAmountInput() {
    (document.getElementById('hidden-amount') as HTMLInputElement).style.display = 'block';
    let input = document.getElementById('amount') as HTMLInputElement;
    input.style.display = 'none';
  }

  showAmountInput() {
    (document.getElementById('hidden-amount') as HTMLInputElement).style.display = 'none';
    let input = document.getElementById('amount') as HTMLInputElement;
    input.style.display = 'block';
    input.focus();
  }

Upvotes: 0

Abhishek Shah
Abhishek Shah

Reputation: 1424

Angular is come up with Pipe concept from it's @angular/common API.

The name of the API which is specially implemented for Currency is CurrencyPipe. Please click on the link which is attached for detailed description.

Answer to you question,

You can use CurrencyPipe directly to you Angular component. Follow below steps to get it work.

  1. Register CurrencyPipe to your respective angular(NgModule) Module under Providers. Please note that it should be imported from @angular/common

    @NgModule({
      declarations: [],
      imports: [],
      providers:[CurrencyPipe]
    })
  2. Inject CurrencyPipe instance to your Angular(Ng) Component and use the method transform to convert the amount in target currency format.

    @Component({
      selector: 'selector-name',
      templateUrl: './design.html',
      styleUrls: ['./design.scss']
    })
    export class YourComponent implements OnInit {
        formGroup: FormGroup;
        constructor(private currencyPipe: currencyPipe, private formBuilder: FormBuilder){
        }
        ngOnInit() {
            const amount = 25.00;
            const amountInCurrencyFormated = this.currencyPipe.transform(amount);
            this.formGroup = this.formBuilder.group({
                amount: amountInCurrencyFormated
            });
        }
    }

Your expected outout: $25.00

Upvotes: 1

Related Questions