Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a value and keep another value in my FormControl?

I'm using text-mask lib and it works pretty well.

Consider the following configuration of mask:

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

In my HTML, I have the following:

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

As you may have noticed, in my mask configuration I'm limiting a field to have a value like this:

9.999.999,99

However, while I want to display this specific format to the user, I'm wanting to get a different value in my control, something like:

9999999,99

Is this possible?

I hope the question is clear enough. Thanks.

Here's a plnkr that I created to illustrate the situation.

like image 469
dev_054 Avatar asked Aug 10 '17 20:08

dev_054


1 Answers

I'd create a directive for this:

@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);
  }    
}

And in HTML, just include numeric attribute:

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

DEMO

like image 116
developer033 Avatar answered Oct 04 '22 21:10

developer033