Angular 2: Using pipes with ngModel

Bryan picture Bryan · Oct 31, 2016 · Viewed 19.9k times · Source

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

Answer

Meir picture Meir · Oct 31, 2016

[(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)"