应用 Angular2 ngModel 后格式化输入值 [英] Format input value after Angular2 ngModel is applied

查看:21
本文介绍了应用 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 后格式化输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆