【问题标题】:Angular 8 - How to use pipes in an input with 2-way data-binding?Angular 8 - 如何在输入中使用带有 2 路数据绑定的管道?
【发布时间】:2019-07-02 10:33:26
【问题描述】:

在 Angular 方面我是一个相对新手,我正在构建一个 Angular 应用程序并希望格式化一个输入字段,用户可以在其中输入他们的收入,并且需要对其进行格式化,以便它都有一个 GBP 符号在它之前并用逗号将值分隔为数千。

因此,例如,用户将其收入添加为 34000,它将显示为 £34,000

我正在尝试使用管道来帮助我实现这一目标,并且我已经尝试使用 CurrencyPipe 和常规管道,但我都遇到了同样的问题。因此,例如,我将使用数字管道:

<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" />

但是,这给了我以下错误:

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

我在使用 CurrencyPipe 时也会遇到同样的错误。我认为这与 ngModel 使用 2 路数据绑定这一事实有关,因为我使用的是在其他地方输入的值。但我似乎根本找不到解决方案,我在这里和其他地方都查看了各种类似的问题。

任何帮助将不胜感激。

【问题讨论】:

    标签: angular typescript angular-pipe angular8


    【解决方案1】:

    我会推荐使用 ngx-mask: https://www.npmjs.com/package/ngx-mask
    它使用起来非常简单,页面上有很多示例:
    https://jsdaddy.github.io/ngx-mask-page/main


    在您的情况下,它将是: &lt;input type='text' prefix="£" mask="comma_separator.2" &gt; 然后解析为代码中的数字类型

    【讨论】:

    • 谢谢。我将首先尝试@SiddAjmera 的解决方案,但如果不起作用,我会看看这个。
    • 他的回答更针对您的问题,所以如果您不希望掩盖其他任何内容,那么他​​的解决方案可能会更好,但是 ngx-mask 为其他场景(如自定义掩码管道)提供了更多工具,所以无论如何我都会去看看。
    • 谢谢!我认为他的解决方案是最好的,因为我不希望掩盖任何其他内容,但如果这种变化我会牢记您的解决方案。再次感谢!
    • 我去年从 ng2-currency-mask 切换到 ngx-mask,因为货币掩码对我来说不能正常工作。我真的很喜欢 ngx-mask 库,它适用于 2-way ngModel 绑定。
    【解决方案2】:

    如果你愿意为此使用第三方库,可以使用ng2-currency-mask

    1. npm install ng2-currency-mask --save
    2. CurrencyMaskModule 添加到要在其中使用它的模块的imports 数组中。
    3. 像这样使用它:&lt;input currencyMask [(ngModel)]="value" [options]="{ prefix: '£ ', thousands: ',', precision: 0 }"/&gt;

    这里有一个Working Sample StackBlitz 供您参考。

    【讨论】:

    • ng2-currency-mask 没有被维护
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2020-01-25
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2017-10-25
    • 2023-03-30
    相关资源
    最近更新 更多