【问题标题】:Angular 4 Currency Pipe with Input Text Field带有输入文本字段的 Angular 4 货币管道
【发布时间】:2019-11-17 19:19:07
【问题描述】:

我有一个输入字段,我想在网络用户 (USD) 输入数据时显示正确的货币格式...

对此有一点背景,我之前使用的输入掩码会向后开始(例如:如果用户输入 10,而不是显示 $10,它会显示 0.10...所以如果用户想显示 $100.00,用户必须输入 1 和 4 个零才能实现这一点...)

跳转到今天的位置...我希望能够在输入字段中输入“10”,然后在输入字段中实时显示为正确的美元货币格式:10.00 美元。

<div class="col-6 col-sm-6 col-md-2 col-lg-1 form-group" *ngIf="configuration.is_item_price_and_total_visible;">
     <mat-form-field floatLabel="never">
       <input matInput type="text" placeholder="Price" [(ngModel)]="selected_item_price | currency:'USD' (ngModelChange)="selected_item_price=$event" name="price">
     </mat-form-field>
</div>

【问题讨论】:

  • 如何保证1和4个零一定是100?如果他需要输入10000怎么办?您的意思是在用户输入值后添加尾随.00
  • 根据我的用户要求,如果用户输入不带任何小数点的 100,则假定输出值为 $100.00 -- 如果用户输入 10000,则假定输出值为:$10,000.00 - 我们说的是否相同东西?
  • Bonci,在您将这个链接发布到 currencypipe 的几分钟内...我可以向您保证,在发布此内容之前我花了好几个小时...是的...我有已访问过此网址,但仍有问题。
  • 所以只是为了澄清一些事情......如果我打印出 {{selected_item_price |货币}} - 它完全按照它应该的方式工作......问题是它没有发生在输入本身......当我尝试使用上面的双向绑定方法将管道放在 ngModel 上时它不起作用 -我收到一条错误消息。

标签: angular angular4-forms


【解决方案1】:

您不能在模板语句中使用模板表达式运算符(管道、保存导航器)。即 [ngModel]="selected_item_price | currency:'USD'"

尝试解析输入值属性,如

<div class="col-6 col-sm-6 col-md-2 col-lg-1 form-group" *ngIf="configuration.is_item_price_and_total_visible;">
      <mat-form-field floatLabel="never">
       <input matInput type="text" placeholder="Price" [value]="selected_item_price| currency:'USD':true:'1.0-2'" [(ngModel)]="selected_item_price" name="price">
      </mat-form-field>
</div>

【讨论】:

    【解决方案2】:

    您需要将绑定拆分为单向绑定[ngModel]="selected_item_price | currency:'USD'" 和事件绑定(ngModelChange)="selected_item_price=$event",因为管道仅适用于单向绑定。

    <mat-form-field floatLabel="never">
      <input matInput type="text" placeholder="Price" [ngModel]="selected_item_price | currency:'USD'" (ngModelChange)="selected_item_price=$event" name="price">
    </mat-form-field>
    

    在从ngModel 中删除() 后,您还可以使用(blur)="selected_item_price = $event.target.value"(keyup)="selected_item_price = $event.target.value" 事件来更新selected_item_price

    【讨论】:

      猜你喜欢
      • 2011-02-24
      • 2018-06-27
      • 2018-07-18
      • 2017-01-16
      • 2017-10-09
      • 2016-01-02
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多