【问题标题】:Angular - bind different values to view and modelAngular - 将不同的值绑定到视图和模型
【发布时间】:2018-05-07 17:25:37
【问题描述】:

我有一个这样的输入字段:

<input type="text" id="myValue" [ngModel]="richiesta.myValue" 
formControlName="myValue" (change)="onValueChange($event.target.value)">

输入的是货币,所以我希望用户能够写 12345(数字),并且该字段的格式应该是这样的:12.345,00 €(字符串) 我的问题是我想保留原始输入的数字以保存到数据库中。
有没有办法做到这一点?谢谢。

编辑
在@ConnorsFan 回答后,我编辑了我的代码,但它仍然无法正常工作,该值未格式化。我错过了一些进口吗?这是我的代码。
查看

    <input type="text" class="form-control" id="myValue" [ngModel]="richiesta.myValue | currency:'EUR':true" formControlName="myValue"
(change)="onValueChange($event.target.value)">

组件

onValueChange(e){
    console.log(e)
    console.log(this.richiesta.value.myValue)
  }

app.module

import { LOCALE_ID, NgModule, Pipe, PipeTransform } from '@angular/core';
...
providers: [{provide: LOCALE_ID, useValue: 'it-IT'}]

EDIT2
我正在寻找解决问题的方法,发现this question 与我的类似。我使用了接受的答案建议的方法,现在我的视图如下所示:

<input type="text" class="form-control" id="myValue" 
(ngModelChange)="richiesta.myValue = $event" 
[ngModel]="richiesta.myValue | currency:'EUR':true"
formControlName="myValue"
placeholder="Importo Finanziamento (€)" (change)="onValueChange($event.target.value)">

管道似乎可以工作,但ngModelChange 在输入的每个数字处都会触发。因此,如果我输入 12345,我会得到 1,00 €2345 以及相应的错误:InvalidPipeArgument: '1,00 €2345' for pipe 'CurrencyPipe'。有没有办法解决这种副作用?

【问题讨论】:

  • 为 onValueChange($event.target.value) 事件处理程序添加组件代码

标签: angular input data-binding formatting


【解决方案1】:

您可以使用CurrencyPipe 格式化字段中的值:

[ngModel]="richiesta.myValue | currency:'EUR':true"       (for Angular 2 and 4)
[ngModel]="richiesta.myValue | currency:'EUR':'symbol'"   (for Angular 5)

正如 Benedikt 的 this answer 中所述,还可以指定区域设置。您可以在onValueChange 中随意将数值保存到数据库中。

This plunker 展示了如何使用以下代码为 Angular 4.2.4 完成此操作:

import { Component, NgModule, LOCALE_ID } from '@angular/core'
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser'
import { CommonModule } from '@angular/common';

@Component({
  selector: 'my-app',
  template: `<h1>Angular 4 - Currency formatting</h1>
  <input [ngModel]="amount | currency:'EUR':true" (change)="onValueChange($event.target.value)" name="inputField" type="text" />
  `
})
export class App { 
  public amount: number = 1234;

  public onValueChange(value): void {
    this.amount = value;
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule, CommonModule ],
  declarations: [ App ],
  providers: [{ provide: LOCALE_ID, useValue: 'it-IT' }],  
  bootstrap: [ App ]
})
export class AppModule {}

【讨论】:

  • 我试过了,恐怕这只适用于双花括号内。
  • 根据我的测试(见this plunker),它也适用于ngModel
  • 嗨@ConnorsFan,我更新了我的代码。您的解决方案很好,但对我不起作用,而如果我执行类似 {{richiesta.myValue |货币:'EUR':true}}。
  • 您使用的是哪个版本的 Angular?加载应用程序时,您是否在控制台中看到任何错误?
  • 我刚刚发布了另一个编辑。我正在使用 Angular 4.2.4,在我第一次编辑的代码中我没有看到任何错误。
猜你喜欢
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 2013-04-05
相关资源
最近更新 更多