0

I've got a component where I'm trying to enforce maxlength by truncating anything the user types over its maxlength.

Here's how I'm doing that:

if (element.maxLength) {
  if (element.value.length >= element.maxLength) {
    this.parts[part] = parseInt(element.value.substr(0,element.maxLength));        
  }
}

this.parts is a collection of three inputs. part is sent in through the update function and is used to refer to the specific input.

Whenever the maxlength is reached (or exceeded), I set the value on the model to a substring from 0 to maxlength. This is setting the correct value of this.parts[part], but it's not showing up in the view. What'm I doing wrong?

Here's my template:

<input type="number" id="ssn3" [(ngModel)]="parts.a" maxlength="3" autotab="ssn2" (input)="update('a',$event.target)" />-
<input type="number" id="ssn2" [(ngModel)]="parts.b" maxlength="2" autotab="ssn4" (input)="update('b',$event.target)" />-
<input type="number" id="ssn4" [(ngModel)]="parts.c" maxlength="4" (input)="update('c',$event.target)" />

Autotab is a custom directive I wrote that can tab to the next input whenever maxlength is reached. This prevents the first two inputs from having values longer than their maxlength, but not the last one, of course

Alex Kibler
  • 4,674
  • 9
  • 44
  • 74
  • Can you show us your template code? – Maximilian Riegler Jun 23 '16 at 15:30
  • Sure, just added it – Alex Kibler Jun 23 '16 at 15:32
  • I don't have an in-depth explanation as to why this happens with the `(input)` event, but it seems that the `[(ngModel)]` wins over the `(input)` event. I have created a Plunker for your example: http://plnkr.co/edit/F9wuoqCbMFUCwUn9Mlwl?p=preview . The first version is what you are currently doing, the second version uses the `keydown` event and prevents any input when the maximum size is exceeded. – Sjoerd Jun 23 '16 at 16:02
  • Something like http://stackoverflow.com/questions/37800841/input-mask-fields-in-angular2-forms/37887432#37887432 might work in your case. You can also try to change the value inside a `setTimeout(...)` function in `update()` to get change detection invoked again after the value changed. – Günter Zöchbauer Jun 23 '16 at 16:09
  • @Sjoerd Strange... changing it to `keydown` (or keyup, which I prefer) worked just fine. I guess I'll stick with that.. – Alex Kibler Jun 23 '16 at 16:53
  • @AlexKibler you are dealing with input field user may perform actions with only mouse.. Ex: Ctrl+Cut and paste .. It dont seems to me keyup will work in that case – mayur Jun 24 '16 at 04:16
  • Yeah, you're right.. but `(input)` isn't working, so I don't know how to work with cut/paste – Alex Kibler Jun 24 '16 at 17:53

0 Answers0