我在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 回答
你是为输入而不是输出添加管道? {{inputValue |货币}}
正如我之前所说,你不应该使用管道来改变 Value . 相反,尝试一个getter / setter .
并从html中删除所有管道内容 .