How to use pipes in Angular 5 reactive form input

AngularAngular Reactive-FormsAngular Pipe

Angular Problem Overview


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 have tested in other areas of the code so I know it works as a simple pipe. My pipe name is 'udpCurrency'

The closest answer I could find on stack overflow was this one: https://stackoverflow.com/questions/39642882/using-pipes-within-ngmodel-on-input-elements-in-angular2-view However this is not working in my case and I suspect it has something to do with the fact that my form is reactive

Here is all the relevant code:

The Template

<form [formGroup]="myForm" #f="ngForm">
  <input class="form-control col-md-6" 
    formControlName="amount" 
    [ngModel]="f.value.amount | udpCurrency" 
    (ngModelChange)="f.value.amount=$event" 
    placeholder="Amount">
</form>

The component

import { Component, OnInit, HostListener } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class MyComponent implements OnInit {
  myForm: FormGroup;

  constructor(
    private builder: FormBuilder
  ) {
    this.myForm = builder.group({
      amount: ['', Validators.required]
    });
  }    
}

The error:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined: '. Current value: 'undefined: undefined'

Angular Solutions


Solution 1 - Angular

This is what can happen when you mix template driven form and reactive form. You have two bindings fighting each other. Choose either template driven or reactive form. If you want to go the reactive route, you can use [value] for your pipe...

Note, this pipe is rather only for showing the desired output in the view.

<form [formGroup]="myForm">
  <input 
    [value]="myForm.get('amount').value | udpCurrency"
    formControlName="amount" 
    placeholder="Amount">
</form>

Solution 2 - Angular

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:

<form [formGroup]="myForm">
  <input formControlName="amount" placeholder="Amount">
</form>

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.

Solution 3 - Angular

I was going to write a custom control, but found that overriding the "onChange" from the FormControl class via ngModelChange was easier. The emitViewToModelChange: false is critical during your update logic to avoid recurring loop of change events. All piping to currency happens in the component and you don't have to worry about getting console errors.

<input matInput placeholder="Amount" 
  (ngModelChange)="onChange($event)" formControlName="amount" />
@Component({
  providers: [CurrencyPipe]
})
export class MyComponent {
  form = new FormGroup({
    amount: new FormControl('', { validators: Validators.required, updateOn: 'blur' })
  });

  constructor(private currPipe:CurrencyPipe) {}

  onChange(value:string) {
    const ctrl = this.form.get('amount') as FormControl;

    if(isNaN(<any>value.charAt(0))) {
      const val = coerceNumberProperty(value.slice(1, value.length));
      ctrl.setValue(this.currPipe.transform(val), { emitEvent: false, emitViewToModelChange: false });
    } else {
      ctrl.setValue(this.currPipe.transform(value), { emitEvent: false, emitViewToModelChange: false });
    }
  }

  onSubmit() {
    const rawValue = this.form.get('amount').value;

    // if you need to strip the '$' from your input's value when you save data
    const value = rawValue.slice(1, rawValue.length);

    // do whatever you need to with your value
  }
}

Solution 4 - Angular

The other answers here didn't work properly for me but I found a way that works very well. You need to apply the pipe transform inside the reactive form valueChanges subscription, but don't emit the event so it doesn't create a recursive loop:

this.formGroup.valueChanges.subscribe(form => {
  if (form.amount) {
    this.formGroup.patchValue({
      amount: this.currencyMask.transform(form.amount)
    }, {
      emitEvent: false
    });
  }
});

This also requires that your pipe "unformats" whatever was there, which is usually as simply as something like this inside your pipe's transform function:

value = value.replace(/\$+/g, '');

Solution 5 - Angular

Without knowing your pipe code, it's likely throwing errors because of where you're constructing that form.

Try using Angular's change detection hooks to set that value after inputs have been resolved:

export class MyComponent implements OnInit {
  myForm: FormGroup;

  constructor(private builder: FormBuilder) { }    

  ngOnInit() {
    this.myForm = builder.group({
      amount: ['', Validators.required]
    });
  }

}

Solution 6 - Angular

Use only this code

<input [value]="value | udpCurrency"  name="inputField" type="number" formControlName="amount" />

Solution 7 - Angular

You could wrap the pipe into a directive. For example:

import { Directive, Input, OnInit } from '@angular/core';
import { NgControl } from '@angular/forms';

// The selector can restrict usage to a specific input.
// For example: 'input[type="number"][yourPipe]' for number type input.
@Directive({ selector: 'input[yourPipeSelector]' })
export class FormControlYourPipeDirective implements OnInit {
  /** Your optional pipe args. Same name as directive to directly pass the value. */
  @Input() public yourPipeSelector: unknown;
  
  /** Control event options. For example avoid unintentional change events. */
  private eventOptions = {
    onlySelf: true,
    emitEvent: false,
    emitViewToModelChange: false,
  };

  constructor(private ngControl: NgControl, private yourPipe: YourPipe) {}

  public ngOnInit(): void {
    this.ngControl.control.valueChanges.subscribe((value) => {
      this.ngControl.control.setValue(
        this.yourPipe.transform(value, this.yourPipeSelector),
        this.eventOptions
      );
    });
  }
}

Don't forget to add YourPipe to the providers in your pipe module. And add the pipe module to the imports of your module where you want to use it. (Angular basics) ... And then use it:

<input formControlName="myValue" [yourPipeSelector]="'some args'" />

Voila

But note: You manipulate an input element that can be edited again by the user. The value should be compatible to the input (and its type).

For example: If you have an input[type="number"] and use the DecimalPipe, you should set an value typeof number to the input control instead of the typeof string which the number pipe returns.

Also note that this only works if you don't prevent event emission (emitEvent). Otherwise you should simply transform your value on the place where you set the value.

Also take a look to updateOn option of FormControl. For example set to blur to avoid annoying changes during user input.

Solution 8 - Angular

<input type="text" name="name" class="form-control mw-120 text-right"
 [value]="finalRow.controls[i].get('rental').value |currency">

This is most efficient as you are not overriding the value with formControlName.

Adding formControlName will not work correctly always, so need to take care.

<input type="text" name="name" class="form-control mw-120 text-right"
 [value]="finalRow.controls[i].get('rental').value |currency" formControlName="rental">

This may not give the resuts expected.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDallas CaleyView Question on Stackoverflow
Solution 1 - AngularAT82View Answer on Stackoverflow
Solution 2 - AngularDallas CaleyView Answer on Stackoverflow
Solution 3 - AngularDrewView Answer on Stackoverflow
Solution 4 - AngularinorganikView Answer on Stackoverflow
Solution 5 - Angularjoh04667View Answer on Stackoverflow
Solution 6 - Angularosama mostafaView Answer on Stackoverflow
Solution 7 - AngularDominikView Answer on Stackoverflow
Solution 8 - AngularAmit SinghView Answer on Stackoverflow