Issues with KeyboardEvent keydown in Angular 2 causing malfunction

I need help with triggering a keydown event that changes the pressed key to a comma. If a non-numeric value is entered, it should simulate the comma and write it in the textbox. However, after the second call, the comma is not displayed. Any suggestions on how to fix this issue?

Thank you.

<input type="text" (keydown)="validate($event)" />


validate(event) {

    if (!this.validatenumeric(event)) {
      event.preventDefault();

    } else {
        if(event.key!==","){
        event.preventDefault();
        var getterCode = { get: function () { return 188 } };
        var getsourceCapabilities = { get: function () { return event.sourceCapabilities } };
        var e = new KeyboardEvent("keydown", {
          altKey: false,
          bubbles: true,
          cancelable: true,
          code: "Comma",
          composed: true,
          ctrlKey: false,
          key: ",",
          detail: 0,
          location: 0,
          metaKey: false,
          repeat: false,
          shiftKey: false,
          view: window
        });

        Object.defineProperties(e, {

          which: getterCode,
          keyCode: getterCode,
          sourceCapabilities: getsourceCapabilities
        });

            this.elementRef.nativeElement.querySelector('input').dispatchEvent(e);

          }
        }
      }


 validatenumeric(key) {
    var keycode = (key.which) ? key.which : key.keyCode;
    //comparing pressed keycodes
    if ((keycode >= 48 && keycode <= 57)) {
      // 0-9 only
      return true;
    } else if ((keycode >= 96 && keycode <= 105)) {
      // 0-9 only
       return true;
    }
    else return false;

    return false;
  }

Update: I may have found a solution by handling keyup events instead of trying another keydown event. By checking for commas, locating the cursor position, and inserting the comma accordingly, I believe this approach could work. Any input or advice would be appreciated!

> <input type="text" (keydown)="validate($event)"
> (keyup)="validateUp($event)" />
> 
>   validateUp(event) {    
>     let pos = this.elementRef.nativeElement.querySelector('input').selectionEnd;
>     if (event.key == ',' ) {
>       this.textValue = text.slice(0, pos) + event.key + text.slice(pos);
>       }   
>   }
> 
> 
>   validateWithtDecimals(event) {
>     var text: string = this.textValue;
> 
> 
>     if (!this.validatenumeric(event, text, this.separator)) {
>       event.preventDefault();
>     }
>     else {
> 
>        if(event.key!==","){
>         event.preventDefault(); 
>       
>         var getterCode = { get: function () { return 188 } };
> 
>         var e = new KeyboardEvent("keyup", {
>           altKey: false,
>           bubbles: true,
>           cancelable: true,
>           code: "Comma",
>           composed: true,
>           ctrlKey: false,
>           key: ",",
>           detail: 0,
>           location: 0,
>           metaKey: false,
>           repeat: false,
>           shiftKey: false,
>           view: window
>         });
> 
>         Object.defineProperties(e, {
>           which: getterCode,
>           keyCode: getterCode,
>         });
> 
>         this.elementRef.nativeElement.querySelector('input').dispatchEvent(e);
>       }
>     }   
>   }

Answer №1

I suggest utilizing data binding over keyboard events for better user experience:

 <input type="text" [(ngModel)]="validatedValue" />

In the component.ts file:

 private _validated = '';
 get validatedValue(): string {
     return this._validated;
 }
 set validatedValue(value: string) {
     value = value.replace('.',',');
     // Add your validation logic here
     this._validated = value;
 }

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

After restoring my Windows system, I encountered an issue with locating the typescript.js module for my Angular app development. I am currently troubleshooting the build

My PC had some issues, so I decided to restore Windows to an older restoration point. However, after doing this, I encountered an error while trying to build my Angular App: C:\Udemy\AngularDeCeroAExpertoEdicion2021\03-paisesApp>npm run ...

Ensure that the tooltip remains visible within the confines of the page

In my Angular application, I have successfully implemented a versatile tooltip feature that goes beyond just displaying text. The tooltip is a div element that has the ability to contain various contents: .tooltip-master { position: relative; .tooltip ...

Retrieve content from my Tumblr API posts

Looking to retrieve my tumblr posts through an api. Successfully set up the api key using Angular2 and typescript. Utilizing jsonp to avoid any cross origin problems. Here is my current code snippet: var config = { params: { action: "query" ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

Creating a composite object in Angular 2 reactive forms: a step-by-step guide

These are the two classes I have: export class Machine { name = ''; computer = new Computer() } export class Computer { os = ''; } Then in my component, using reactive forms, I have: ngOnInit() { this.form = this.fb ...

What is the correct way to interact with an Object's functions in TypeScript?

I'm facing a challenge with one of the libraries I'm using as it is throwing a lot of TypeScript errors related to Object functions. The list of TS errors that I encountered include: error TS2339: Property 'random' does not exist on t ...

Navigating VSCode for Correct Import Setup

My root app directory has a structure consisting of the following folders: /app/ /environments/ Within the /app/ folder, there is a file named Helper.ts located in the helpers/ subdirectory: /app/helper/Helper.ts Inside this file, I attempted to import ...

Ensure the clarity tabs labels have the padding-left CSS property added

In my project, there are 2 clarity tabs (you can view the StackBlitz reference here). https://i.sstatic.net/jhLcn.png I want to apply the padding-left property specifically to Tab1 (the tab label itself, not the content) in order to create some space aro ...

Have you considered utilizing encodeURIComponent to encode both the key and parameter values?

When I use encodeURIComponent in this code snippet: export function getDownloadFileUrl(fid: string,bgColor: string) { const params = encodeURIComponent("id=" + Number(fid) + "&bgColor=" + bgColor); const config = { m ...

Generating formarray instances in Angular using data from MySQL records

I am currently working on a project where I need to populate formcontrols in formarray based on the data retrieved from a MySQL database. However, when I pass the success data from MySQL, I encounter an error that says "Cannot read property 'controls& ...

Is it necessary to utilize RequestHandler every time I create an Endpoint in Sveltekit?

As I work on creating a Todo website, I came across a video tutorial about building a Svelte fullstack app. The teacher in the video demonstrated the use of RequestHandler to create an endpoint. However, in the SvelteKit documentation, it recommends using ...

Encountering a VersionError with Mongoose and MongoDB: Unable to find a document matching the ID "60bf5b73de309f1a30fe88a2" and version 10, with modified paths including "likes"

While developing my fullstack application (a Facebook clone), I encountered an error in my server that I am struggling to resolve. The technologies I am using include node.js, express, MongoDB, Mongoose, and TypeScript. The error occurred during the devel ...

Type 'Partial' cannot be assigned a value when combining interfaces with generic types

Consider the following scenario: class Table<ValuesType extends DefaultTableValues = DefaultTableValues>{ public values: ValuesType; constructor(initialValues:ValuesType) { this.values=initialValues; } public set(newValues:Pa ...

Angular: Leveraging real-time data updates to populate an Angular Material Table by subscribing to a dynamic data variable in a service

Seeking guidance on how to set up a subscription to a dynamic variable (searchData - representing search results) for use as a data source in an Angular Material Table. I have a table-datasource.ts file where I want to subscribe to the search results from ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Solana Metaplex Maker Dispute Resolved

Currently experimenting with the Metaplex Storefront, I have incorporated 2 whitelisted wallets for my auction page through the admin section (one of which was used to initialize the page). I conducted a test auction with this particular NFT () that has 2 ...

Dealing with name conflicts in Typescript when using multiple interface inheritance

Is it possible to securely implement two interfaces in Typescript that both have a member of the same name? Can this be achieved? For example: interface IFace1 { name: string; } interface IFace2 { name: string; } class SomeClass implements IFace ...

Encountering an npm package resolution error despite following all of the necessary requirements

error message: ERESOLVE Unable to resolve dependency Issues encountered while resolving: @ionic/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52333c35273e332012657c667c60">[email protected]</a> Found: <a href ...

Creating an Angular FormControl that can toggle multiple buttons

Here is the object I am currently working with currentApplication = { 'Initial': [12, 2, true, true, false], 'Reminder1': [8, 2, true, true, false], 'Reminder2': [4, 2, true, true, false], ...

The header code in Angular 6 does not get triggered when working with the router

After successfully validating the username and password, I perform the following action: this.router.navigate(['./home']); Each page includes a header with the following content: <ng-container *ngIf='isAuthenticated'> <li c ...