Convert a number to currency format in Angular 10
Asked Answered
M

1

2

I am using Angular 10 and imported the CurrencyPipe from '@angular/common' and based on the suggestions found, I implemented the following in the template -

<p>{{Amount | currency}}</p>

This shows the amount value in $ and with commas like expected but doesn't show the value in the textbox field but rather on top of the textbox. Please see the screenshot below -

Screen capture showing the value on top of the text box

How can I assign this value to the [Value] attribute so that it is displayed in the textbox?

Miskolc answered 5/7, 2022 at 21:50 Comment(1)
Thinking this question is what you need: Using Pipes within ngModel on INPUT Elements in AngularMallet
P
0

It's a question large dicuss. I feel that the better bet is use a directive

import { NgControl } from '@angular/forms';
@Directive({
  selector: '[onblur]',
})
export class BlurFormatDirective implements OnInit {
  @Input('onblur') transform: (string) => string | null;
  @HostListener('blur') onBlur() {
    if (this.transform && this.control)
      this.el.nativeElement.value = this.transform(this.control.value);
  }
  @HostListener('focus') onFocus() {
    if (this.transform && this.control)
      this.el.nativeElement.value = this.control.value?
                                       this.control.value:'';
  }
  constructor(
    private el: ElementRef,
    @Optional() @Host() private control: NgControl
  ) {}

  ngOnInit() {
    setTimeout(() => {
      this.onBlur()
    });
  }
}

Now we can use some like

<input [onblur]="transform" [(ngModel)]="name">

where

 name = 'Angular ' + VERSION.major;

  transform(value:string)
  {
    //e.g. transform a string
    return value.split('').map((x,i)=>i%2?x:'*').join('');
    //or
    return formatCurrency(+value,'en-GB',"$")
  }

see stackblitz

NOTE: This directive only work for template driven forms or Reactive Forms

Pard answered 6/7, 2022 at 7:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.