Angular 2: Using pipes with ngModel

ぐ巨炮叔叔 提交于 2019-12-18 04:12:49

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/40346676/angular-2-using-pipes-with-ngmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!