本文介绍了应用Angular2 ngModel后格式化输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一条指令,将输入值格式化为货币格式.

I am trying to create a directive that will format the input value to a currency format.

我能够执行聚焦和模糊处理,在ngOnInit挂钩(和其他挂钩)中,输入元素尚未应用任何值.

I am able to do what I have to do on focus and on blur, and in the ngOnInit hook (and any other hook), the input element does not yet have any values applied to it.

如何监视"输入的值,并在应用其初始值时对其进行格式化?

How do I "watch" for the input's value, and format it when it's initial value is applied?

这是我的指令:

import {
  Input,
  Directive,
  HostListener,
  ElementRef,
  Renderer,
  OnInit
} from '@angular/core';
import { NgModel } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';

@Directive({
  selector: '[currencyInput]',
  providers: [NgModel],
  host: {
    '(input)': 'onInputChange()'
  }
})
export class CurrencyInputDirective implements OnInit {
  @Input() ngModel: number;

  private elem: HTMLInputElement;

  constructor(
    private el: ElementRef,
    private render: Renderer,
    private currencyPipe: CurrencyPipe,
    private model: NgModel,
  ) {
    this.elem = el.nativeElement;
  }

  ngOnInit() {
    this.elem.value = this.currencyPipe.transform(parseInt(this.elem.value), 'USD', true);
  }

  @HostListener('focus', ['$event.target.value'])
  onFocus(value: string) {
    this.elem.value = value.replace(/\,/g, '');
  }

  @HostListener('blur', ['$event.target.value'])
  onBlur(value: string) {
    this.elem.value = this.currencyPipe.transform(parseInt(value), 'USD', true);
  }
}

推荐答案

一种可能性是绑定到getter/setter方法,该方法会将字段转换为正确的格式,然后将其恢复为原始格式.修改,如下所示

One possibility is to bind to a getter/setter method that will transform the field to the correct format, and then return it back to the original format after it is modified, as per below

打字稿:

 AnnualRevenue: number;
  get AnnualRevenueFormatted():string{
    return  this.AnnualRevenue !== undefined ?  `$${this.AnnualRevenue.toLocaleString()}`: '$0';
  }

  // strip out all the currency information and apply to Annual Revenue
  set AnnualRevenueFormatted(val: string) {
    const revenueVal = val.replace(/[^\d]/g, '');
    this.AnnualRevenue = parseInt(revenueVal);
  }

以及在组件视图中

<input type="text" class="text-input" [(ngModel)]="accountInfo.AnnualRevenueFormatted"  />

这篇关于应用Angular2 ngModel后格式化输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:31