The directive for accepting only numbers is not functioning in versions of Chrome 49.xx.xx and earlier

I have implemented a directive in Angular 6 to allow only numbers as input for certain fields. The directive code is shown below:

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[NumbersOnly]'
})

export class NumbersOnlyDirective {
  // Allow decimal numbers and negative values
  private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['ArrowLeft', 'ArrowRight', 'Backspace', 'Tab', 'End', 'Home'];

  constructor(private el: ElementRef) { }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    const current: string = this.el.nativeElement.value;
    const next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

The directive is utilized in input fields like so:

<input [(ngModel)]="sendLinkMobile" NumbersOnly type="text" id="mobile-num"  
class="form-control m-no" placeholder="Mobile Number"  requried  minlength="10" 
maxlength="10" aria-label="Recipient's username" aria-describedby="basic-addon2">

While the code works flawlessly on modern browsers, mobile devices, and tablets, it encounters issues when used on older versions of Chrome (49.xx and below), where the input fields fail to accept any values. I would appreciate any assistance in identifying and rectifying the problem.

Thank you in advance.

Answer №1

Utilize this directive and test it out. It seems to function properly on chrome version 49.xx

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class Onlynumber {

  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    if (this.OnlyNumber) {
      if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+C
        (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+V
        (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+X
        (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
          // allow key events to proceed as normal
          return;
        }
        // Ensure that only numbers are inputted
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
      }
  }
}

HTML:

<input OnlyNumber="true"  type="text" #numberModel="ngModel" [(ngModel)]="numberModel"  name="numberModel" />

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

Utilizing D3 for translation by incorporating data from an array within d3.js

I need assistance with drawing rectangles in an SVG where the translation data is stored in an array. Below is the code: var vis=d3.select("#usvg"); var rectData=[10,21,32,43,54,65,76,87,98,109]; vis.selectAll("rect").data(rectData).enter().append("rect ...

Ways to apply CSS in jQuery using various combinators

I'm facing an issue with changing CSS using jQuery. The specific CSS line I want to modify is: .switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside { top: 40px; } My attempt at changing it looked like this: $('.switch-vertic ...

Obtain data in JSON format through an xmlhttp request

I originally used jQuery for this task, but I now want to switch to regular JavaScript as I'll be incorporating it into phonegap. I aim to avoid relying on different JS frameworks every time I make a server request, which could potentially improve per ...

Is there a way to apply a decorator to a function that has been returned?

Can the following be accomplished? bar () { @custom yield () => { } } ...

Sluggish website loading time

Hey there, I'm currently developing a website and I'm facing a major issue with one of my pages loading slowly and experiencing lag. I'm unsure if this is due to the on scroll listeners or the excessive references in my code. Could it possib ...

What causes req.sessions to show an empty object instead of the expected value?

I've been grappling with a small issue while learning express.js. I am struggling to save sessions in the browser so that users don't have to log in every time they visit. I am using cookie-session for this purpose. When I send the login data fro ...

Organize AngularJS ng-repeat using dictionary information

I'm dealing with a dictionary consisting of key-value pairs, which looks something like this: data = { "key1": 1000, "key2": 2000, "key3": 500 } My goal is to display this data in a table using AngularJS. One way I can achieve this is b ...

Obtaining a JSON reply using Ember

Exploring new possibilities with Ember js, I am eager to switch from fixtures to using an API. Below is the code I have implemented to fetch the data: App.ItemsRoute = Ember.Route.extend({ model: function() { return $.getJSON('http://som ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Containerizing Next.js with TypeScript

Attempting to create a Docker Image of my Nextjs frontend (React) application for production, but encountering issues with TypeScript integration. Here is the Dockerfile: FROM node:14-alpine3.14 as deps RUN apk add --no-cache tini ENTRYPOINT ["/sbin ...

Steps to set angular for all items in the dropdown menu:

I am currently working on implementing a dropdown feature within my Angular application. The dropdown will display a list of shops, and when a shop is selected, it will show the content related to that particular shop. I need to add a new item called "ALL ...

Encountering a parsererror with $.ajax while processing JSON that includes a new Date() object

After fetching JSON from a MongoDB database, I serialize it and send it back to the JavaScript client using a $.ajax call. Here is an example of the $.ajax call: function server_request(URL, httpMethod, dataObject) { var output = ""; var typeofD ...

Invoke a function of a child component that resides within the <ng-content> tag of its parent component

Check out the Plunkr to see what I'm working on. I have a dynamic tab control where each tab contains a component that extends from a 'Delay-load' component. The goal is for the user to click on a tab and then trigger the 'loadData&apo ...

Invoking a plugin method in jQuery within a callback function

Utilizing a boilerplate plugin design, my code structure resembles this: ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.pro ...

What is Angular's approach to handling elements that have more than one directive?

When an element in Angular has multiple directives, each specifying a different scope definition such as scope:false, scope:true, or scope:{}, how does the framework handle this complexity? ...

An anomaly with the checkbox editing feature in the PrimeNG table

Within my Angular 5 application, I am utilizing the PrimeNG "turbo" table component and encountering an issue while trying to edit a checkbox. If you want to learn more about PrimeNg tables, visit primeNg - table https://i.sstatic.net/ryZ2A.gif As depict ...

Confused about how to implement lambda expressions in Angular 2?

Snippet of Angular 2 Code heroes => this.heroes = heroes; I am curious to know the precise meaning of this particular line. Can anyone explain? ...

Nested loops with synchronous calls running in parallel

Is there a way to make synchronous calls in two nested 'for' loops in Node.JS? I have an Asynchronous call, but I am unsure how to modify it to work synchronously and go to the next iteration when create_db is done! var new_items = []; f ...

How can I transfer a value from one form to another using AngularJS?

Trying to retrieve the Id from a table and pass it to a controller, however, I am facing an issue where the Id value is lost every time the form changes. Is there a better way to handle this? Below is the service and controller code: //Retrieving IdValue ...

The GitHub Pages website is not displaying exactly like it does when running locally with a live server

Currently in the process of creating a compact website where users can input an anagram and receive all potential words that can be formed from it. Additionally, upon receiving these words, there is an option to click on one for its definitions. The site ...