0

I have the following input

<input
  [(ngModel)]="myInput"
  mask="00-0000-0000||00-00000-0000"
  type="text"
>

and I would like to initialize it with a certain value. Let's say 12-12345-1234.

This doesn't work since I only see 12-1234-5123 (The last digit is cut out of the html input and the shortest possibble mask is being used).

I would like to be able to initialize my input with any valid value and see the correct mask applied to it.

Damian Kociszewski
  • 283
  • 1
  • 5
  • 20

1 Answers1

-3

To setup a DOM initial Value, you can use the value attribute on the HTML template:

<input type="text" value="any-value-here">

The mask you are trying to use is a production of DOM manipulation logic. It will be achived by running JavaScript code, which modifies the DOM, and depending on the framework you use, or the lib you create the input mask effect, will always overwrite that 'initial' value.

In you case, using [(ngModel)] is not a strict initialization: it's already a value binding "event" made by angular as far as I know. To test your logic, I think it would be a better approach to create tests, or add the mask dynamically to the field if possible.

ForestG
  • 17,538
  • 14
  • 52
  • 86
  • 1
    So I've decided to add the mask dynamically, right after the user inputs some value. – Damian Kociszewski Sep 16 '20 at 10:15
  • @DamianKociszewski how do you solved that? – Patrick Freitas Mar 23 '21 at 18:00
  • Well, I am NOT proud of my solution, but I've declared my mask as a BehaviorSubject with an initial value of null. I am waiting for the input to get initialized and depending on the initial input value I am passing the next value (mask) to the mask BehaviorSubject. If I subscribe to the mask value with the async pipe, I can dynamically change its mask. So basically I am kind of cheating by not providing the mask on init. – Damian Kociszewski Mar 26 '21 at 10:41