Angular 8 directive for concealing phone numbers

I am currently facing an issue with my phone mask directive that is designed to accept US format phone numbers. The problem arises when I try to clear the input by deleting one character at a time using the backspace key, as the value in the input field doesn't get emptied. This issue came to light only after I logged the input value of the form.

Interestingly, if I clear the entire input at once, it does get emptied. However, clearing the input one character at a time always leaves one digit behind.

https://i.sstatic.net/Tg6HMm.png

Does anyone know how to ensure the input value gets cleared when the form value is empty?

For reference, I have provided a functional example using StackBlitz. Can someone assist me with this issue?

Here is my Directive:

export class PhoneMaskDirective {
  constructor(public ngControl: NgControl) {}

  @HostListener("ngModelChange", ["$event"])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener("keydown.backspace", ["$event"])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

  onInputChange(event, backspace) {
    if (event == null) {
      return "";
    }
    let newVal = event.replace(/\D/g, "");

    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    if (newVal.length === 0) {
      newVal = "";
    } else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, "($1)");
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, "($1) $2");
    } else if (newVal.length <= 10) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, "($1) $2-$3");
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
}

Answer №1

It seems that the issue lies in setting a null value when the input value length is equal to 0 using valueAccessor.writeValue, which is not effective in this context.

Would you consider replacing this

this.ngControl.control.setValue(null);

with

this.ngControl.valueAccessor.writeValue(null);

Check out the reference link for more information: https://stackblitz.com/edit/angular6-phone-mask-4rzs1k?file=app%2Fphone-mask.directive.ts

Answer №2

It is highly recommended to utilize @HostBindings and @HostListeners instead of relying on the host property

Simply delete the host and incorporate @HostListener

@HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

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

Template specific requirements in Angular

When I have a child component app-page-header, here's what I want to achieve: If the value of headerOptions.headerTitle is not 'Idle Disposition', then set [titleData] to equal 'headerOptions.headerTitle'. However, if headerOptions ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Variations in jQuery's append method when dealing with a string, a reference to a jQuery object

Here are multiple ways to add a div element to the body of an HTML document. But what distinctions exist between them and in what scenarios should each be utilized for optimal performance? var newDiv = '<div id="divid"></div>'; $(&ap ...

Track and manage date ranges inclusive of specific times

http://jsfiddle.net/7vzapm49/1/ var startdatearr = [new Date("04 Dec 2014 14:30:00").toUTCString(), new Date("07 Dec 2014 14:30:00").toUTCString()]; var enddatearr = [new Date("05 Dec 2014 14:30:00").toUTCString(), new Date("08 Dec 2014 14:30:00").toUTCSt ...

Issue with Intel XDK: the document.location.href is directing to an incorrect page

Hello Community of Developers, I have been experimenting with different methods but still haven't found a solution. In my project using Intel XDK, whenever I attempt to change the page using location.location.href = "#EndGame" or similar codes in Java ...

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. https://i.sstatic.net/jQ62l.png .html <ion-slides [pager]="true" [slide ...

"Revolutionary jQuery plugin designed to function independently of HTML elements

Is it possible to create a jQuery plugin that can be executed without the use of an element selector? Typically, we use: $('#myElementID').myPluginFunction(myVariables); But, is there a way to do it like this instead? $.myPluginFunction(my ...

What are all the different methods I can use to transfer element A to element B, and what are those methods?

While experimenting with Jquery, I encountered a roadblock and now have this question in mind. I wish to enclose all the anchor elements within a newly created div element. <td class="cont-mod-none-options" valign="top" align="right"> <a hr ...

Searching for a string enclosed in square brackets using regular expressions

To effectively extract multiple words within square brackets using preg_match_all(), I need to create three regular expressions. For example: Input string: Lorem [ipsum] dolor sit [[amet]], nam you dolores detracto definitionem. Et admodum fabellas pa ...

Order a portion of a JSON array according to another part of the same array

Having a json array that needs sorting in JavaScript. The EventName field should match the respective Age fields like 01-10 Days and 10-20 Days. [ {Age: "01-10 Days", EventName: "Invoice AP Review", Value: 1, ActiveInvoices: []} ,{Age: "01-10 Days", Even ...

Tips for showcasing checkbox options on an HTML page (utilizing ejs) following the retrieval of information from MongoDB and making it editable for the User

Currently, I store data in mongo for a multiple-choice question and indicate the correct answers. In mongo, I save them like this: question.options.option1.check = "on" for the correct answers. When I navigate to the "edit" page, I retrieve the specific ...

Create an interactive quiz using JQuery that focuses on sorting and organizing

Hey there, I need some advice on creating a quiz for ordering and sorting in HTML5/JQuery. Basically, I want to display a random set of steps on the page that users have to organize correctly. I found an example using jQuery and jquery-ui-1.8.5.custom.min. ...

Encountering a TypeError while pre-rendering a page during the npm run build process

I am currently preloading this page on my Next.js application: const router = useRouter(); if (!router.isFallback && !postData?.slug) { return <p>Hmm... looks like an error</p> } const formatDate = date => { const newDa ...

The Highchart Angular directive is failing to update when receiving new data from a dynamic (ajax) data table

My AngularJs application fetches data from an API and populates a table with it. I then use Highcharts to create a chart based on the table data. Everything works fine when I use static data in the table, but it doesn't update properly when I try to c ...

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

Easy ways to manipulate the style of array components in Vue.js

Hey there all you programmers, I'm reaching out to see if any of you have insight on how I can modify the style of a specific component within an Object array. This is the code snippet: <template> <div> <ul> <li v-fo ...

a JavaScript method in Selenium for performing a double-click action on a WebElement

Since selenium allows for the execution of JavaScript, I am interested in clicking and double-clicking on a web element or x, y coordinate using JavaScript. I prefer to use JavaScript because the web element in question is a Flash/SVG object on the browser ...

Does JSON have a special reserved key for identifying the time?

I've noticed an interesting issue when logging the json string of a key labeled tid - it always shows up as 0. Take a look at this example: var transaction = {tid:1, type:0, time:126312736}; var transStr = JSON.stringify(transaction); console.log(tra ...

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...