2017-08-10 66 views
2

我正在使用text-mask lib,它工作得很好。如何显示一个值并在FormControl中保存另一个值?

考虑的以下配置掩盖

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以说明情况。

回答

2

我会为此创建指令:

@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

相关问题