Error message: Invalid input for directive, only numeric values are accepted

I need help with a directive that restricts non-numeric symbols in an input field.

Below is the code for the directive:

  import { NgControl } from "@angular/forms";
import { HostListener, Directive } from "@angular/core";

    @Directive({
      exportAs: "number-directive",
      selector: "number-directive, [number-directive]",
    })
    export class NumberDirective {
      private el: NgControl;
      constructor(ngControl: NgControl) {
        this.el = ngControl;
      }
    
      @HostListener("input", ["$event.target.value"])
      onInput(value: string): void {
        this.el.control.patchValue(value.replace(/[^0-9]/g, "").slice(0));
      }
    }

Here is an example of how to use it in an input field:

  <input
  type="text"
  tabindex="0"
  class="search__input form-control-md + {{class}}"
  [value]="config.value"
  [required]="config.required"
  [attr.maxlength]="config.maxLength"
  [attr.minLength]="config.minLength"
  #inputElem
  number-directive
/>

Even after implementing the directive, I can still input text like aaaaa. What could be causing this issue?

Answer №1

Identified two potential root causes:

  1. Issue may arise from neglecting to include NumberDirective in the declarations section of app.module.ts.

    To resolve this, ensure that you add NumberDirective to declarations in app.module.ts for registering the directive.

@NgModule({
  ...
  declarations: [..., NumberDirective],
})
export class AppModule {}
  1. No provider found for NgControl regarding your <input> element.

    This issue may result in an error message due to the absence of [(ngModel)] for the input element. The directive expects it to be a NgControl, hence requiring the presence of [(ngModel)].

    Alternatively, consider using

    [formControl]="configControl"
    for your <input> element.

Error: R3InjectorError(AppModule)[NgControl -> NgControl -> NgControl]: NullInjectorError: No provider for NgControl!

<input
  type="text"
  tabindex="0"
  class="search__input form-control-md + {{ class }}"
  [value]="config.value"
  [required]="config.required"
  [attr.maxlength]="config.maxLength"
  [attr.minLength]="config.minLength"
  #inputElem
  number-directive
  [(ngModel)]="config.value"
/>

OR

<input
  type="text"
  tabindex="0"
  class="search__input form-control-md + {{ class }}"
  [value]="config.value"
  [required]="config.required"
  [attr.maxlength]="config.maxLength"
  [attr.minLength]="config.minLength"
  #inputElem
  number-directive
  [formControl]="configControl"
/>
configControl = new FormControl();

View Example Solution on StackBlitz

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

Calculating the sum of all words that have been successfully finished

My spelling game includes words of different sizes ranging from 3 to 6 letters. Once a certain number of words are completed in the grid, the remaining grid fades away. Instead of only considering one word size at a time, I want the game to calculate the t ...

Verification of user input upon clicking the submit button within a form

I am encountering an issue with validating my form, as no errors are displayed in the console. I have followed the instructions provided by Bootstrap documentation but to no avail. My aim is to implement a feature where clicking on the button triggers an a ...

Postpone the initial click action triggered by the specified directive

Is it possible to create a directive that prompts for confirmation when a button is clicked? This would involve storing the original event and only executing it once the user confirms their choice. A similar behavior has been mocked here: https://stackbl ...

Filtering an array of <input> values in JavaScript based on the number of characters they contain

Can someone help me figure out why this JavaScript code isn't working as expected? The intention is to grab the input value from a text box (a string of words separated by spaces), convert it into an array, and then remove any words that are less than ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

When navigating to '/blogs/', the index.js file in Next.js will automatically open

I'm working on a project using next.js and I want to ensure that when I visit 'localhost:3000/blogs/', it opens the index.js page. The index.js file is located in the 'blogs' folder of my project. Currently, it does open properly ...

I encountered an issue where the error "data.map is not a function" occurs whenever I try to execute a React component

I have implemented the HorizontalScrollbar component and passed data as a prop. When I try to run the HorizontalScrollbar component, I encounter the following error in the console tab of Chrome: Error: Uncaught TypeError: data.map is not a function Horiz ...

Tips for setting limitations on a date picker's minimum and maximum values on an iPhone using JavaScript

I have encountered an issue with my JavaScript function that sets min and max values for the input type date. While it works perfectly on Android devices, I am facing a problem on iPhone where I am unable to restrict the calendar with the specified min and ...

Cookie Multitree: An Innovative JsTree Solution

Hello everyone, I am currently using jstree and have come across a couple of issues with having multiple trees on the same page. Here are my two problems: 1) I am looking to implement cookies to keep track of which nodes are open in each tree. I attempted ...

What are some effective methods for testing internet connectivity?

My CMS operates by pulling large amounts of data using PHP, MySQL, jQuery, Bootstrap, and AJAX. An issue arises when the internet connection is lost, causing problems with displaying and scrolling on the site. I am interested in finding a solution that c ...

Sending a parameter to a request-promise function within an iteration through a forEach loop

I have successfully implemented an API call for price data. However, I am facing an issue while trying to pass the variable exchange_pair_id into the then() function. Within the forEach loop, the exchange_pair_id is accurate for each asset. But inside the ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

A custom JavaScript function designed to replicate Excel's functionality of dividing numbers by thousands

I've noticed a unique behavior in Excel where when a cell is in focus and you enter, for example, 1500.32, it displays as 1 500.32. However, once you click enter or move away from the cell, it changes to 1 500.32. I'm intrigued by how this works. ...

Controlling opacity with jQuery animate() function using a click event

I have a specific requirement for an animation. When the button is clicked, I need the element to transition from 0 opacity to full 1 opacity within 300 milliseconds. The issue I am facing is that when the button is clicked, the animation does not work a ...

Discovering the operating system and architecture type for my browser using Node.js - what steps should I take?

I am currently developing a Node.js app that serves as an API microservice. I need to retrieve the operating system and architecture type from a GET request made by my browser. One example could be: "Windows NT 10.0; Win64; x64" ...

The color input click event does not work properly when triggered within a context menu event

This may sound a bit complicated, but let me try to explain it clearly. I'm working on a web app where I want users to be able to change the background color of certain divs. I plan to use a color picker interface for this purpose and utilize the con ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...

I encountered an error while using the router: TypeError: Cannot read property 'use' of undefined

Hello everyone, I am new to node.js and seeking help from experts. I am currently working on a code for user synchronization using node.js + AWS Cognito + Facebook Login. I followed an example from this link. Everything was going smoothly until I reached ...

Executing JavaScript's addEventListener() function without specifying the event that triggers it

I am currently working on creating a grid of boxes that can be clicked, sending notifications with their respective IDs to the server using SocketIO. <body> <div class="wrapper"> <div id="1" class="box"></div> <div id="2 ...

Unable to conceal adjacent element when z-index is set as 1

I encountered an issue where a modal is overlapping another element, and the close button of the underlying element has a z-index of 1. Despite creating a new modal with its own close button, the original close button remains visible on top. I attempted t ...