angular – 如何在FormControl中显示值并保留另一个值?

前端之家收集整理的这篇文章主要介绍了angular – 如何在FormControl中显示值并保留另一个值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 text-mask lib,它运行得很好.

考虑以下掩码配置:

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

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

9999999,99

这可能吗?

我希望这个问题足够清楚.谢谢.

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

解决方法

我会为此创建一个指令:

@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中,只包含数字属性

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

DEMO

猜你在找的Angularjs相关文章