Angular 2: Using pipes with ngModel
Asked Answered
T

1

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)]?

Tautologism answered 31/10, 2016 at 16:44 Comment(0)
M
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)"
Mutable answered 31/10, 2016 at 16:57 Comment(4)
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.Tautologism
But where is the error itself? What's the stack? Does it get to your update handler?Mutable
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.Traceable
so you can add to your Amount a .startWith('')Mutable

© 2022 - 2024 — McMap. All rights reserved.