I have created a pipe to format the value in the input box as follows:
1 123
10 123
101 123
2 101 123
23 101 123
123 101 123
The pipe gives the desired output when I type into the input box or hit backspace.
Issue: The input box does not update when I remove a space from the Input box.
e.g. If I changed value from 123 123 to 123123 the input box does not update.
The pipe:
@Pipe({name: 'formatCurrency'})
export class FormatCurrencyPipe implements PipeTransform{
transform(value: string): string {
//convert to string
value = value.toString();
// remove spaces
value = value.replace(/ /g,'');
console.log('Spaces removed');
console.log(value);
// add spaces
value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
console.log('Spaces Added');
console.log(value);
return value;
}
}
HTML:
<input type="text" (keypress)="disableSpace($event)" [ngModel]="data.value | formatCurrency" (ngModelChange)="data.value = $event" />
Component:
export class App implements OnInit {
name:string;
data:any = {value: 123345};
constructor() {}
ngOnInit(): void {
this.name = 'Angular2';
}
disableSpace(event: any) {
if (event.charCode && event.charCode === 32 || event.which && event.which === 32) {
event.preventDefault();
}
}
}
Plunker: https://plnkr.co/edit/j5tmNxllfZxP0EDp2XgL?p=preview
Any idea why this behavior and how to fix/approach this problem?