【问题标题】:How to display a value and keep another value in my FormControl?如何在我的 FormControl 中显示一个值并保留另一个值?
【发布时间】:2018-01-19 06:00:36
【问题描述】:

我正在使用text-mask lib,它运行良好。

考虑下面的mask配置:

priceMask = Object.freeze({
  mask: createNumberMask({
    allowDecimal: true,
    decimalSymbol: ',',
    integerLimit: 7,
    prefix: '',
    thousandsSeparatorSymbol: '.'
  })
});

在我的 HTML 中,我有以下内容:

<form [formGroup]="formGroup">
  <input type="text"
         formControlName="maskedInput"
         [textMask]="priceMask">
</form>

您可能已经注意到,在我的掩码配置中,我将字段限制为具有如下值:

9.999.999,99

但是,虽然我想向用户显示这种特定格式,但我想在我的 control 中获得不同的值,例如:

9999999,99

这可能吗?

我希望问题足够清楚。谢谢。

这是我创建的plnkr 来说明这种情况。

【问题讨论】:

    标签: angular angular2-forms angular-reactive-forms


    【解决方案1】:

    我会为此创建一个指令:

    @Directive({
      selector: '[numeric]'
    })
    
    export class NumericDirective {
    
      constructor(private model: NgControl) { }
    
      @HostListener('input') inputChange() {
        const newValue = this.model.value.replace(/\./g, '');
        this.model.control.setValue(newValue);
        this.model.valueAccessor.writeValue(newValue);
      }    
    }
    

    而在 HTML 中,只需包含 numeric 属性:

    <form [formGroup]="formGroup">
      <input type="text"
             formControlName="maskedInput"
             [textMask]="priceMask"
             numeric>
    </form>
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2014-06-19
      • 1970-01-01
      • 2020-07-19
      相关资源
      最近更新 更多