Directive display ng-model input value as currency in angular

倾然丶 夕夏残阳落幕 提交于 2019-12-10 12:26:55

问题


I want to display Currency sign with decimal value in my input field. If model value is set to 2 it should display $ 2.00 while model value should remain numeric. I have created a directive that do so but if load value from server where value is set in model then it display $ 2.00 and model value is also string while i need numeric.After googling many posts i have found this soln but it is in angular 1. How it can be converted in angular 2? I need exactly same behavior: Fiddle

My directive is:

    import { Directive,Renderer,ElementRef,OnInit,Input,Output,EventEmitter,HostListener} from '@angular/core';
import {NgModel} from '@angular/forms';
declare var $: any;
@Directive({
  selector: '[appUiCurrencFormatter]',
  providers: [NgModel],
  host: {
    '(ngModelChange)' : 'onInputChange($event)'
  }
})
export class UiCurrencFormatterDirective implements OnInit {
  private currencyPrefix : string;
  private el: HTMLInputElement;
   @Input() ngModel;
   @Output() ngModelChange = new EventEmitter();
   constructor(public elementRef: ElementRef,public model:NgModel) {
     this.currencyPrefix= "£ ";
     this.el = this.elementRef.nativeElement;
  }
  ngOnInit() {
     let v= this.roundN(this.ngModel,2);
     this.model.control.setValue(v);
     this.model.valueAccessor.writeValue(this.currencyPrefix + v);
     this.ngModelChange.emit(this.currencyPrefix + v);
  }

  roundN(num, n) {
    return (Math.round(num * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n);
  }

  onInputChange(newValue: any):Number {
    debugger;
    return <Number>newValue;
  }
  @HostListener('keydown', ['$event'])
  keyDownEvent(event: KeyboardEvent) {
    if (event.key.length === 1 && (event.which < 48 || (event.which > 57 && event.which<96) || (event.which>106 && event.which!=110)))
    {
      event.preventDefault();
    }
  }

  @HostListener("blur", ["$event.target.value"])
  onBlur(value) {
    var plainNumber = value.replace(/[^\d|\-+|\.+]/g, '');
    let v= this.roundN(plainNumber,2);
    this.model.control.setValue(v);
    this.model.valueAccessor.writeValue(this.currencyPrefix + v);
  }
}

回答1:


After reading this post Format input value after Angular2 ngModel is applied I have applied solution to my directive with little change and it works for me

ngAfterViewInit() {
 this.model.valueChanges.subscribe(value => {
   if(this.counter==1) { //Should call only once not everytime value changes
     let v= this.roundN(value,2);
     this.model.valueAccessor.writeValue(this.currencyPrefix + v);
   }
   this.counter++;
 })

}

Here Counter is private variable and initilize in ngOnInit event of directive



来源:https://stackoverflow.com/questions/49898808/directive-display-ng-model-input-value-as-currency-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!