简体   繁体   中英

Angular 8 - How to use pipes in an input with 2-way data-binding?

I'm a relative newbie when it comes to Angular and I'm building an Angular app and am looking to format an input field where a user inputs their income and it needs to be formatted so that it both has a GBP symbol before it and with commas separating out the value into thousands.

So, for example, a user adds their income as 34000 and it will be displayed as £34,000

I'm trying to use pipes to help me achieve this and I've tried using the CurrencyPipe and regular Pipes and I get the same issues with both. So, for example, with the number pipe I'll have:

<input type="number" (change)="getApp1income()" (keyup)="getApp1income()" [(ngModel)]="app1income | number" [ngModelOptions]="{standalone: true}" min="0" step="500" data-number-to-fixed="2" data-number-stepfactor="500" />

However, this gives me the following error:

Uncaught Error: Template parse errors:
Parser Error: Cannot have a pipe in an action expression at column 14 in [app1income | number=$event]

I'll get the same error when using CurrencyPipe as well. I think this has to do with the fact with the fact that ngModel is using 2-way data-binding as I'm using the value entered elsewhere. But I can't seem to find a solution at all and I've looked at various similar issues both on here and elsewhere.

Any help would be appreciated.

If you're willing to use a third-party library for this, you can use ng2-currency-mask

  1. npm install ng2-currency-mask --save
  2. Add CurrencyMaskModule to the imports Array of the Module that you want to use this in.
  3. Use it like this: <input currencyMask [(ngModel)]="value" [options]="{ prefix: '£ ', thousands: ',', precision: 0 }"/>

Here's a Working Sample StackBlitz for your ref.

I would recommend using ngx-mask: https://www.npmjs.com/package/ngx-mask
It's quite simple to use and it has many examples on its page:
https://jsdaddy.github.io/ngx-mask-page/main


In your case it would be: <input type='text' prefix="£" mask="comma_separator.2" > Then parse to number type in your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM