指令以角度

时间:2018-04-18 11:39:52

标签: javascript angularjs angularjs-directive angular2-directives

我想在输入字段中显示带小数值的货币符号。如果模型值设置为2,它应显示$ 2.00,而模型值应保持数字。我创建了一个指令,但是如果从服务器加载值,在模型中设置值,那么它显示$ 2.00,模型值也是字符串,而我需要数字。在谷歌上搜索了很多帖子后我找到了这个溶液但是它是有角度的1.它如何以角度2转换?我需要完全相同的行为:Fiddle

我的指示是:<​​/ p>

    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 个答案:

答案 0 :(得分:0)

阅读此帖后Format input value after Angular2 ngModel is applied 我已经将解决​​方案应用于我的指令,几乎没有变化,它适用于我

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++;
 })

}

此处Counter是私有变量,并在指令

的ngOnInit事件中初始化