The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within the input field. I utilized the keydown event as the host for this directive. Is this potentially an issue related to Angular itself? Any tips or references to existing posts that could help me resolve this?

EDIT

@Directive({ 
    selector: 'input[allowCurr]',
    host: { '(keydown)': 'allowND($event)' } 
})
export class AllowCurrDirective { 
    @Input() allowCurr: string;
     /* More logic implemented here */ 
} 

I included the code snippet above because I had added an alert inside my allowND function, and while it does trigger, the event.key property (used to capture user input) returns undefined.

Answer №1

After some experimentation, I finally cracked the code. Utilizing event.target.value in conjunction with the input event allowed me to achieve my goal of restricting input to only numbers and a single decimal point within the input box.

:: Investigation ::

If you visit this MDN link on your smartphone browser, you'll notice that for the input event, KeyboardEvent.data behaves similarly to KeyboardEvent.key on desktops. This means you can observe the key pressed on your smartphone keyboard. (I tested this out using W3schools try-it editor on my phone). However, there's a catch - KeyboardEvent.data is not supported on iPhones. Therefore, I couldn't rely on either event.key or event.data. Since the input event cannot be cancelled (event.preventDefault() won't work), if what you type doesn't meet the criteria, the input value should be adjusted as follows:

let targetVal = event.target.value;
event.target.value = targetVal.substring(0, targetVal.length - 1);

Answer №2

Perhaps you should consider using the HostListener functionality

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

@Directive({
  selector: "input[allowCurr]"
})
export class AllowCurrDirective {
  @HostListener("keydown", ["$event"])
  allowND(e) {
    console.log(e.key);
  }
  @Input() allowCurr: string;
  /* Additional logic can be implemented here */
}

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

Find a specific value within a complex array of objects in Angular 2

Recently delving into Angular 2, I am seeking guidance on the best approach for a particular use-case. My array of Objects is structured as follows: users : Array<Object> = [{ id: 1, tags: [{ name: 'foo', age: 21 ...

Is it possible for me to use an NPX tool to execute git clone command?

I am currently working on developing a personalized NPX tool that will install my custom npm package onto a locally hosted server. At the moment, I have a layout template that I want other users to replicate when they run my NPX command. Here is an exampl ...

Applying REGEX on input text in React Native

I'm having trouble getting my regex function to work correctly, so I believe there might be an error in my code. Any assistance would be greatly appreciated. Here is the regex function I am using: let validatePlate = (plate) => { var re = /(^[A ...

JSON and autocomplete feature causing performance problems

Developing an application that functions both online and offline using technologies like application cache and local storage is my current project. Utilizing jQuery mobile along with a jqm autocomplete solution from , I aim to create a seamless user experi ...

Creating a hash map for an iteration through a jQuery collection

Using the jQuery .each function, I traverse through various div elements. By using console.log, the following output is obtained: 0.24 240, 0.1 100, 0.24 240, 0.24 240, The first number on each line represents a factor and the last number is the res ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

execute the function based on the given ID

I've been attempting to dynamically add content using a function. My goal is for the content with the same anchor ID as the clicked anchor to be added, but it seems like nothing is happening. Is there a more effective approach to achieve this? $(&a ...

Which option's value was recently removed from the fetch command?

I created a function to handle duplicate selections in a select element. It is functioning properly, but I noticed that when I remove an option from the select, my array remains unchanged. If I remove an option, I want my code to detect the value of that ...

When constructing a file directory URL, it is important to utilize the forward slash "/" in the filename

As I am creating a URL, the process involves taking the filename and using it to create a folder with that name. However, an issue arises if the name contains "/", as it causes the URL to break and creates an undesired location. For example: var fileDir ...

Transform the string with binary hexadecimal characters in ASCII into a Buffer

Currently, I am utilizing node.js for my project. Within my code, there is a string variable called msg_str that contains the value "0102ab00aabb00". My goal is to convert this ASCII binary hex representation into a Buffer and have it displayed as <01 ...

Top tips for creating effective Angular 2 components

My application features a user object that stores and updates all user information using an observable provided by the userService. I am now contemplating the best practice for utilizing this user observable with components. One specific scenario involves ...

experiencing a problem with the scrollTo() function

I am encountering difficulty in finding the correct X and Y coordinate values to move an image using mouse scroll within a div. I have included my sample code below. I have successfully managed to scroll the image without using a div. Can anyone assist m ...

How to automatically set focus in a text box when a Kendo Window is opened

I am working on a project where I need to set the focus on the first field of a kendo-window when it opens after clicking on a button. I used ViewChild to declare the field, but it is showing as undefined when the window is opened because it hasn't be ...

Set boundaries for the width and height of an image in the input field

Looking to restrict the size of an image in an input field using HTML, CSS, and JavaScript/jQuery. Goal is to maintain a perfect square aspect ratio for profile photo uploads (for example, 200x200 or 300x300). ...

Remove a data entry from the MySQL database by selecting the corresponding row in the table and utilizing the DELETE function

Is there a way to remove a record from my MySQL database by clicking on a row in a table that is generated using ejs? Below is the code I am currently using to generate the table rows. <% res.forEach(function(item){ %> <tr> ...

Electronic circuit embedded within a material-textured text field offering multiline functionality

While experimenting with TagsInput, I came across this helpful snippet on codesandbox that you can check out here. The challenge I encountered is when there are numerous chips, they extend beyond the boundaries of the text field. My goal is to implement ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

The request's body in the PUT method is void

I seem to be having an issue with my PUT request. While all my other requests are functioning properly, the req.body appears to remain empty, causing this error message to occur: errmsg: "'$set' is empty. You must specify a field like so: ...

Adding and Removing Classes from Dynamically Added DOM Elements in Angular 2/4

I'm currently working on creating a unique list, similar to the notification system seen on platforms like Facebook. The list is pulled in via JSON and displayed on the UI using ngFor. Each item in the list has a default CSS class called "unread", whi ...

Issue with Angular *ngIf not rendering properly following retrieval of data from API

I am experiencing an issue with the *ngIf directive. When I retrieve my data in the AppComponent and utilize *ngIf, my Revolution Slider does not display. Without using ngIf When using ngIf This is how my code appears: Service.ts getAllPlaces(languag ...