I am trying to figure out how to use a pipe within a reactive form so that the input is forced into a currency format. I have already created my own pipe for this which I h
I thought I had this working but as it turns out, I was wrong (and accepted a wrong answer). I just redid my logic in a new way that works better for me and answers the concern of Jacob Roberts in the comments above. Here is my new solution:
The Template:
The Component:
import { Component, OnInit, HostListener } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UdpCurrencyMaskPipe } from '../../../_helpers/udp-currency-mask.pipe';
export class MyComponent implements OnInit {
myForm: FormGroup;
constructor(
private builder: FormBuilder,
private currencyMask: UdpCurrencyMaskPipe,
) {
this.myForm = builder.group({
amount: ['', Validators.required]
});
this.myForm.valueChanges.subscribe(val => {
if (typeof val.amount === 'string') {
const maskedVal = this.currencyMask.transform(val.amount);
if (val.amount !== maskedVal) {
this.myForm.patchValue({amount: maskedVal});
}
}
});
}
}
The Pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'udpCurrencyMask'
})
export class UdpCurrencyMaskPipe implements PipeTransform {
amount: any;
transform(value: any, args?: any): any {
let amount = String(value);
const beforePoint = amount.split('.')[0];
let integers = '';
if (typeof beforePoint !== 'undefined') {
integers = beforePoint.replace(/\D+/g, '');
}
const afterPoint = amount.split('.')[1];
let decimals = '';
if (typeof afterPoint !== 'undefined') {
decimals = afterPoint.replace(/\D+/g, '');
}
if (decimals.length > 2) {
decimals = decimals.slice(0, 2);
}
amount = integers;
if (typeof afterPoint === 'string') {
amount += '.';
}
if (decimals.length > 0) {
amount += decimals;
}
return amount;
}
}
Now there are several things i learned here. One was what that what Jacob said was true, the other way only worked initially but would not update when the value had changed. Another very important thing to note was that I need a completely different type of pipe for a mask as compared to a view pipe. For example, a pipe in a view might take this value "100" and convert it to "$100.00" however you would not want that conversion to happen as you are typing the value, you would only want that to happen after were done typing. For this reason i created my currency mask pipe which simply removes non numeric numbers and restricts the decimal to two places.