Encountering issues with pipes and ngModel functionality in Angular causing errors

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!

Answer №1

Avoid using both ngModel and formControlName together. To utilize a pipe, consider using [value] and then binding the formControl value to it for updating the value whenever a new input is inserted:

<form [formGroup]="creditCardForm" (ngSubmit)="submitCreditCardForm()">
  <input 
     [value]="creditCardForm.get('creditCardNumber').value | creditCardMask: true"
     type="text"
     formControlName="creditCardNumber">
</form>

DEMO 🚀🚀

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for dynamically appending data to `from([urls])` using RxJS

const dataResults = []; from(generateMoreUrls()) .pipe( mergeMap( url => fetch(url), 4) ).subscribe(dataResult => { dataResults.push(dataResult); }); function generateMoreUrls() { let additionalUrls = []; for(let i = 101; i < ...

It seems that the Angular2-google-maps library is having trouble with installation

Attempting to install the angular2-google-maps library is resulting in errors. The desired library can be found at: The specific error encountered is displayed here: https://i.stack.imgur.com/L2vOY.png Any assistance with this issue would be greatly app ...

Using SWR, retrieve data in client components consistently for each request in a Next.js version 13.3 environment

I recently upgraded to Next.js 13.3 with the app dir set up. I have a simple component that displays the current date. However, it only updates the date once and then doesn't update again until I rebuild the app. In Next.js 12, the date would update w ...

Determine the variable height of a div containing dynamic content in order to execute a transform

Looking to create a dynamic container that expands when a button/link is clicked? The challenge lies in achieving this expansion effect with a smooth transition. By using the height: auto property, the container can expand to fit its content, but incorpora ...

My inquiry was met with silence from the Angular project

I have encountered an issue with my dockerized angular project. Upon starting my container, it appears that the 4200 port is already in use, even though the CMD command within the container does not initiate the application startup. Here is how my Docke ...

Is there a solution for onBlur() event in Angular 7's ngx-intl-tel-input?

I encountered a problem in Angular 7 while working with the ngx-intl-tel-input package. I am trying to validate a phone number on blur event. <ngx-intl-tel-input [cssClass]="'form-control'" [preferredCountries]="preferredCountries" ...

What is the best way to track upload progress while using Django?

Is it possible to implement an upload progress bar for a website using Django? I'm interested in tracking the progress of file or image uploads but unsure how to accomplish this. Any tips on retrieving the upload status? ...

Logging in using email, phone number, or username on Node.js platform

How can I implement a login system in node.js and MongoDB that allows users to log in with their email, phone number, or username along with a password? Similar to the login functionality seen on Instagram, users should be able to enter their email or u ...

Executing the `writeFile` and `writeFileSync` functions in the Express.js route handler with Node.js causes the front-end page to automatically reload

Encountering an issue with my code where the page unexpectedly reloads when communicating with my backend app. The backend app utilizes functions from the fs module, specifically writeFile/writeFileSync. Oddly enough, when I eliminate these function calls, ...

Interacting with Angular 2 Components Inside <router-outlet>

In the header component, there is a search bar. Below that, within the same component, there is a "router-outlet". After pressing enter in the search bar (input field), the search string (event.target.value) should be sent to the component inside the rou ...

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...

Duplicate items within an array were found when receiving Node.js response data in Angular

I'm facing an issue where duplicate elements are being displayed in an Angular table when receiving data from Node.js. The array sent by Node.js contains 2 elements, but somehow it appears as 4 elements in the Angular table. This discrepancy is puzzli ...

What is the best way to measure the loading time of a "Loading Screen" page using Jmeter and Selenium?

Once a file is uploaded to the website, a loading screen appears depending on the file size. I am interested in measuring how long this loading screen remains active. As a novice in jmeter and programming, I'm unsure if there's a more efficient m ...

Transform the date format from Google Forms to TypeScript

I am currently facing an issue with a Google Form connected to a Google Spreadsheet. The date format in the spreadsheet appears as follows when a response is received: 20/02/2023 18:58:59 I am seeking guidance on how to convert this date format using Type ...

Issues with the play() method in Javascript across Firefox, Safari, and IE 11 are causing functionality problems

I developed a basic video and audio player that smoothly fades out an introductory image and starts or stops playing an mp4 file upon click. Everything functions properly in Chrome, but unfortunately does not work in other major browsers. Despite checking ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

Is there a way to link my ionic application to dual API URLs within a single webpage? Additionally, how can I transfer the ID from the information received from the first URL to the second URL efficiently?

I am currently in the process of developing an Ionic recipe application. The home page is designed to display a list of recipes names, ids, and images by fetching data from an API endpoint at www.forexample/recipeslist.com. My goal is to create functiona ...

Discover the method for selecting an element within a table that includes a style attribute with padding using Jquery

Looking for a way to identify a td element with the padding style in a table I've attempted to locate a td element with the padding style attribute in a table $(Table).find('td[style="padding:"]') or $(Table).find('td[style] ...

Ways to delete a header from the req object in Express

Can anyone help me understand how to remove a header from the req object in Express? I've heard that using res.disable("Header Name") can do this for the res object, but it doesn't seem to work for req.headers. ...

Implementing multiple dropdown menus with Material UI in a navigation bar

I am currently working on designing a navigation bar that consists of multiple material UI dropdown menus. However, I have encountered an issue that has proven to be quite challenging for me to resolve. Whenever I click on a navigation bar item, all the dr ...