【问题标题】:How to use curency pipes in Angular reactive form and Validator如何在 Angular 反应形式和验证器中使用货币管道
【发布时间】:2019-10-16 19:53:33
【问题描述】:

我使用 Angular 响应式表单和验证器(值 > 0)。在我的模型中,我的数据是 BigDecimal(例如 5.80):

this.userInfoFormGroup = this.formBuilder.group({
    money:[this.price, this.positiveVal()], 
});

我使用货币管道:

<input type="text" class="form-control" formControlName="money" [value]="userInfoFormGroup.get('money')?.value | currency:'EUR'">

我的代码可以在线使用HERE

我的问题是原始值 5.8 被管道转换为 5.8 欧元。管道如何只用于展示而不用于模型?

例如,当我将 5.8 更改为 5.9 时,我会重现该问题。但是我的应用程序将 5.8 更改为 5.90 欧元,并且我的验证器是 KO,因为 是 NaN。

【问题讨论】:

    标签: angular angular-reactive-forms angular-pipe


    【解决方案1】:

    你可以试一试:

    <input type="text" class="form-control" formControlName="money" [value]="getNumberVal(userInfoFormGroup.get('money')?.value) | currency:'EUR'">
    
    getNumberVal(val: string): number {
      val = `${val}`;
      return parseFloat(val.replace(/\u20AC/g, ''));
    }
    
    positiveVal(): ValidatorFn {
      return (control: AbstractControl): {[key: string]: any} | null => {
        const invalid = this.getNumberVal(control.value) <= 0;
        return invalid ? {'positiveVal': {value: control.value}} : null;
    };
    

    Full demo在线

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-09
      • 2018-07-18
      • 1970-01-01
      • 2017-01-16
      • 2018-06-27
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      相关资源
      最近更新 更多