I have a unique custom dropdown feature that binds the selected dropdown value to an input field in my reactive form using ngModel. I have also implemented a mask on the input fields using a pipe. Here is all the relevant code for this functionality:
HTML File
<form [formGroup]="creditCardForm" (ngSubmit)="submitCreditCardForm()">
<input
[ngModel]="selectedCard.cardNumberMasked | creditCardMask: true"
(ngModelChange)="selectedCard.cardNumberMasked = $event"
type="text"
formControlName="creditCardNumber">
</form>
TypeScript File
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class MyComponent implements OnInit {
creditCardForm: FormGroup;
constructor(
private builder: FormBuilder
) {
this.creditCardForm = builder.group({
creditCardNumber: ['', Validators.required]
});
}
}
Mask Pipe TypeScript File
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'creditCardMask',
})
export class CreditCardMaskPipe implements PipeTransform {
transform(value: string, showMask: boolean): string {
if (typeof value === 'number') {
value = JSON.stringify(value);
}
if (!showMask || (value.length < 16 && value.length < 15)) {
return value;
}
return `${value.substr(0, 4)} ${'\u2022'.repeat(4)} ${'\u2022'.repeat(
4
)} ${value.substr(value.length - 4, value.length)}`;
}
}
Although using ngModel in a reactive form is deprecated, I need it for binding the value from the selected dropdown. However, I am encountering the following error in console:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined: 512345444444444'. Current value: 'undefined: 5123 •••• •••• 4444'.
Error Message: https://i.sstatic.net/J6AkD.gif
If you have any suggestions or best practices on how to solve this issue, please feel free to share. Thank you!