问题
I've created a custom pipe in Angular 5 that updates the display of an input field on blur.
The value of the input field is converted and displayed, but the value of the model is not updated properly. This is the functionality I am expecting, is there a way to achieve this with a pipe?
Stackblitz - Link to Sample Code
Steps to Reproduce the issue.
Remove the existing value and type in any number and click outside the field. (Eg: 242235.34234)
The input and the model values do not match.
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);
}
}
回答1:
you're adding a pipe for the input but not the output? {{ inputValue | currency }}
回答2:
As i stated before, you shouldn't be using a pipe to morph the value. Instead, try a 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; }
}
and remove all the pipe stuff from the html.
来源:https://stackoverflow.com/questions/53688946/angular-5-pipe-updateonblur-not-updating-model-as-expected