1

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
shravs
  • 21
  • 1
  • 5
  • 1
    Thinking this question is what you need: [Using Pipes within ngModel on INPUT Elements in Angular](https://stackoverflow.com/questions/39642882/using-pipes-within-ngmodel-on-input-elements-in-angular) – Yong Shun Jul 06 '22 at 01:43

1 Answers1

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

Eliseo
  • 50,109
  • 4
  • 29
  • 67