首页 文章

Angular 5 Pipe,{updateOn:'blur'}未按预期更新模型

提问于
浏览
0

我在Angular 5中创建了一个自定义管道,用于更新模糊输入字段的显示 .

转换并显示输入字段的值,但不正确更新模型的值 . 这是我期望的功能,有没有办法通过管道实现这一点?

Stackblitz - Link to Sample Code

Steps to Reproduce the issue.

删除现有值并键入任意数字,然后单击该字段外部 . (例如:242235.34234)

输入和模型值不匹配 .

HTML Code:

<h1>Currency Pipe</h1>

<div>
  Input:
  <input type="text" [ngModel]="inputValue | currency" name="inputValue"
    [ngModelOptions]="{updateOn:'blur'}" (ngModelChange)="inputValue=$event"/>
</div>

<div>{{ inputValue }}</div>

Angular Pipe:

import { Pipe, PipeTransform } from '@angular/core';
import * as accounting from 'accounting';

@Pipe({
  name: 'currency'
})
export class CurrencyPipe implements PipeTransform {

  private format = { precision: 2, thousand: ',', decimal: '.' };

  transform(value: string): any {

    let formattedValue = accounting.unformat(value);
    return accounting.formatNumber(formattedValue, this.format);
  }

}

2 回答

  • 1

    你是为输入而不是输出添加管道? {{inputValue |货币}}

  • 1

    正如我之前所说,你不应该使用管道来改变 Value . 相反,尝试一个getter / setter .

    import { Component } from '@angular/core';
    import * as accounting from 'accounting';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      private $inputValue;
      private format = { precision: 2, thousand: ',', decimal: '.' };
    
      set inputValue(value){
        let formattedValue = accounting.unformat(value);
        this.$inputValue = accounting.formatNumber(formattedValue, this.format);
      } 
    
      get inputValue(){ return this.$inputValue; }
    }
    

    并从html中删除所有管道内容 .

相关问题