10

I was using JQuery inputmask in one of my forms along with [(ngModel)], but for some reason they won't work together. Using either one by itself works perfectly fine, but combining the two completely breaks [(ngModel)] and new inputs don't get sent back to the component. After struggling with this for a while I figured using Angular 2's pipes would be a good solution, however I can't figure out how to get those two to work together either.

Here is some code I am using for testing my pipe

<input [(ngModel)]="Amount" id="Amount" name="Amount" class="form-control" type="number" autocomplete="off">
<p>Amount: {{Amount | number:'1.2-2'}}</p>

If I type in 12345, the <p> tag below will show 12,345.00, which is exactly how I want it to filter, but I don't want to have the filtered amount below the input, I want the input itself to display 12,345.00. Adding that same pipe to the ngModel like this: [(ngModel)]="Amount | number:'1.2-2'" gives me the following error.

Parser Error: Cannot have a pipe in an action expression at column 10 in [Amount | number:'1.2-2'=$event]

How can I use pipes (or input masks) inside an input with [(ngModel)]?

Bryan
  • 2,951
  • 11
  • 59
  • 101

1 Answers1

28

[(ngModel)] is a short hand for [ngModel] and (ngModelChange). If you separate them it should work (it works for sure with the async pipe):

[ngModel]="Amount | number: '1.2-2'" (ngModelChange)="updateAmount($event)"
Meir
  • 14,081
  • 4
  • 39
  • 47
  • I see, that worked great, although now I'm having an issue with the cursor position, but I should probably post a new question for that. – Bryan Oct 31 '16 at 17:12
  • 1
    But where is the error itself? What's the stack? Does it get to your update handler? – Meir Oct 31 '16 at 17:24
  • The error is throwing in the decimal pipe when the value is empty: Invalid argument '' for pipe 'DecimalPipe' and it's happening on the handler when the input value is empty. I think it's Angular bug for not protecting empty values. – Bazinga Oct 31 '16 at 17:28
  • so you can add to your Amount a `.startWith('')` – Meir Oct 31 '16 at 18:35