Directive for masking input values

I am in need of an input that adheres to the following format:

[00-23]:[00-59]

Due to the limitations of Angular 2.4, where the pattern directive is unavailable and external libraries like primeNG cannot be used, I have been attempting to create a directive for this purpose:

@HostListener('keyup', ['$event']) onKeyUp(event) {
    var newVal = this.el.nativeElement.value.replace(/\D/g, '');
    var rawValue = newVal;
    
    // default format for empty value
    if(newVal.length === 0) {
        newVal = '00:00';
    } 
    // do not display colon for empty groups at the end
    else if(newVal.length === 1) {
        newVal = newVal.replace(/^(\d{1})/, '00:0$1');
    } else {
        newVal = newVal.replace(/^(\d{2})(\d{2})/, '$1:$2');
    }
    
    // set the new value
    this.el.nativeElement.value = newVal;
}

This implementation works as intended for the first two digits entered.

Initial string:

00:00

After pressing the number 1:

00:01

Subsequently pressing the number 2:

00:12

However, upon entering a third digit, the result is:

00:123

Instead of 01:23, and 00:1234 rather than 12:34

Despite this issue, backspacing functions correctly.

Is there a solution to this challenge that solely involves using a directive?

Answer №1

Give this a shot in your latest attempt:

replace(/^(\d{0,2})(\d{0,2})/g, '$1:$2')
. Hopefully, it does the trick.

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

Exploring techniques to compare two objects in JavaScript and then dynamically generate a new object with distinct values

var person1={ name:"Sarah", age:"35", jobTitle:"Manager" } var person2={ name:"Sarah Sanders", age:"35", jobTitle:"Manager" } //the name value has been updated in the above object, s ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

When using an Angular client to send a request with an access token to Azure AD WebAPI, the response may still show

I have been facing an issue with my Angular client while trying to authenticate and receive a token from Azure AD. Despite adding the token to the header and calling the WebAPI, I keep encountering the message: "Authorization has been denied for this requ ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

Tips for resolving TS7022 issue within Vue Composition API

I encountered an issue while attempting to import a component in my file that generated the following error message: TS7022: 'default' implicitly has type 'any' because it does not have a type annotation and is referenced directly or in ...

Encountering null injector errors when running ng test on an Angular application

I have successfully developed a webpage in my Angular application and it is running perfectly. But, when I run ng test, some errors are popping up in Karma like the one shown in the image below: superuser.component.ts // Code for superuser component das ...

Obtain the Enum's Name in TypeScript as a String

I am currently looking for a solution to transform the name of an enum into a string format. Suppose I have the following Response enum, how can I obtain or convert 'Response' into a string? One of my functions accepts any enum as input and requi ...

Error: Navbar component cannot access static member

I am encountering the error message Static member is not accessible at this particular point: auth.service.ts export class AuthService { public static get isLoggedIn() { const user = JSON.parse(localStorage.getItem('user')); return (u ...

The Angular material table is having compilation issues due to an unexpected closing tag for "ng-container"

Currently, I am in the process of working on an Angular project that involves integrating Angular Material version 5.2.5. Below is a snippet from my app.component.ts: import { Component } from '@angular/core'; import {MatTableDataSource} from & ...

Utilizing a GLTF asset as the main Scene element in a Three.js project

I'm struggling with incorporating a gltf model as the main scene in Three.js. Specifically, I have a gltf model of an apartment that I want to load from inside and not outside the apartment. I also need the controls to work seamlessly within the apart ...

New Authentication: The sign-in feature will redirect to /api/auth/error

Currently implementing Google sign-in functionality on my Next.js 13 app using Next-auth. I have utilized the signIn() function as described in the documentation here. However, upon calling the signIn() function, I am unexpectedly redirected to http://loca ...

Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing. In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data an ...

Debugging TypeScript on a Linux environment

Approximately one year ago, there was a discussion regarding this. I am curious to know the current situation in terms of coding and debugging TypeScript on Linux. The Atom TypeScript plugin appears promising, but I have not come across any information ab ...

Choose a phrase that commences with the term "javascript"

I need assistance in creating two unique regular expressions for the following purposes: To select lines that begin with 'religion'. Unfortunately, my attempt with /^religion/g did not yield any results. To match dates and their correspondi ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

Redirecting to an Unverified Website

I encountered an issue in my service.ts file where VeraCode code scan is failing Flaws by CWE ID: URL Redirection to Untrusted Site ('Open Redirect') (CWE ID 601)(16 flaws) Description The web application is vulnerable to URL redirection attacks ...

Encountering CircularJSON Error While Creating Angular CLI 7 Project

Recently updated Angular CLI to version 7.1.1 and encountered an issue when trying to create a new project using ng new project-name. The error message displayed is: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

What is the best way to utilize Typescript when making queries to Firebase?

I have successfully integrated push notifications for my app using Firebase Cloud Functions. Now, I am looking to enhance the user experience by updating the app's badge count alongside the push notifications. I understand that this can only be achiev ...

Setting options using the form group in dropdowns in Angular can greatly enhance the user experience

I have created a FormGroup called holidayform and set it up as follows: holidayform: FormGroup; this.holidayform = this.fb.group({ title: ['', [Validators.required]], entryDate: ['',], }) this.holidayform.patchValue ...