Tips for including a dash or hyphen in an input field after two digits in Angular 4

Struggling to format the date of birth input with dashes manually when entered by the user. The desired output should resemble "08-18-2019," but I'm having difficulty achieving this.

 public dateOfBirth: { year: number; month: number; day: number };

html file

 <input
          ngbDatepicker
          dobMask
          #d="ngbDatepicker"
          #dobF="ngModel"
          class="form-control input-underline input-lg"
          id="dob"
          [(ngModel)]="dateOfBirth"
          placeholder="mm-dd-yyyy"
          name="dp"
          [ngClass]="{
            invalid:
              (dobF.value === null || isString(dobF.value) || futureDate) && dobF.touched
          }"
          required
        />

Implemented a directive, but the result displayed as "11---------3."

Directive code snippet:

@Directive({
selector: '[dobMask]'
})
export class DobDirective {

@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;

let trimmed = input.value.replace(/\s+/g, '');
if (trimmed.length > 8) {
  trimmed = trimmed.substr(0, 8);
}

let numbers = [];
for (let i = 0; i < trimmed.length; i += 2) {
  numbers.push(trimmed.substr(i, 2));
}

input.value = numbers.join('-');

  }
}

Current result: Imgur link not provided

Desired outcome: Should display as "08-17-2019."

Any guidance on how to achieve the expected formatting?

Answer №1

Made some adjustments to your directive, and it now works perfectly fine.

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

@Directive({
selector: '[dobMask]'
})
export class DobDirective {

@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;

let trimmed = input.value.replace(/\s+/g, '');

if (trimmed.length > 10) {
  trimmed = trimmed.substr(0, 10);
}


trimmed = trimmed.replace(/-/g,'');

 let numbers = [];
  numbers.push(trimmed.substr(0,2));
 if(trimmed.substr(2,2)!=="")
 numbers.push(trimmed.substr(2,2));
 if(trimmed.substr(4,4)!="")
 numbers.push(trimmed.substr(4,4));
input.value = numbers.join('-');

  }
}
  1. The initial issue was that you were trimming with a length of 8 instead of 10 (including '-').

    1. Additionally, in your loop, you were incrementing by 2 which wouldn't work for the required 4 values in the last item.

    2. It's also important to remove the '-' before proceeding with the logic.

Please have a look at this:

https://stackblitz.com/edit/angular-8dnjfw

Answer №2

To implement ngModelChange, consider the following approach:

<input [ngModel]="dateOfBirth" (ngModelChange)="updateDateOfBirth($event)">

Next, in the controller .ts file:

updateDateOfBirth(dob) {
  // Implement logic to add hyphens if dob is in a valid format
  // Pseudocode:
  // IF dob matches required format THEN
  //   dob = dob with hyphens added
  this.dateOfBirth = dob
}

The date of birth will be updated in the form control due to the binding [ngModel]="dateOfBirth"

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

Angular: Oops! Encountered some template parsing issues: Surprising closing tag encountered

Recently, I created a brand new project with Angular CLI on 05/25/17. I decided to copy and paste some HTML code into a new component in the project. Surprisingly, this HTML code, which worked perfectly fine as its own standalone page, is now causing compi ...

Troubleshooting TypeScript in Visual Studio Code

Currently, I'm attempting to troubleshoot the TypeScript code below using Visual Studio Code: class Student { fullname : string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + ...

Issue with event.stopPropagation() in Angular 6 directive when using a template-driven form that already takes event.data

I am currently developing a citizenNumber component for use in forms. This component implements ControlValueAccessor to work with ngModel. export class CitizenNumberComponent implements ControlValueAccessor { private _value: string; @Input() place ...

Inverting a mask using NumPy

Is there a method to invert the true/false values in a numpy masked array? For instance, if I have the data array below, how can I mask out the first and third values instead of the second value? The following is just an example as my masked array is gen ...

updating firebase data using Angular

Currently, I am attempting to insert a new object into my Firebase database export class AppComponent { courses$: AngularFireList<any[]>; course$;ang author$ constructor(db: AngularFireDatabase) { this.courses$ = db.list('/courses ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

What is the reason why the [active] attribute does not function properly in <a mat-tab-link> in Angular?

<div class="d-flex d-column themed-tab-nav"> <nav mat-tab-nav-bar color="primary" [tabPanel]="tabPanel" mat-stretch-tabs="false" mat-align-tabs="start"> <a mat-tab-l ...

`Only encountering CORS access-control-allow-origin issue when using Safari browser`

We have an Angular application that communicates with a .NET Core RESTful API project. In addition, we have a separate authentication application (Identity Server4) responsible for managing logins. This issue is specific to Safari; all other browsers are ...

API response containing JSON data is not being displayed properly in the webdatarocks angular component

I can't seem to figure out how to properly display the JSON formatted data returned by a REST API using Angular. Any suggestions on how to accomplish this? Here's what I've been attempting to do - fetchData() { this.service.fetchData().s ...

Angular frontend failing to send authorization cookie for cross-origin requests, despite using withCredentials

Today, I've been facing a persistent issue that I just can't seem to figure out. I have my Angular frontend running on localhost:4200 and a Spring Boot backend on localhost:8080. When I call the localhost:8080/api/login endpoint from my Angular ...

What is the process for generating flexible paths (URL strings) in angular applications?

Within my <app-parent> component, I have multiple buttons that each open a new floating panel on top of the parent. These floating panels also contain buttons that trigger the opening of additional floating panels, creating a stacking effect. My go ...

Examining form functionalities: angular2 form testing

Currently, I'm facing an issue while attempting to test a component that utilizes 'FormGroup' and 'FormBuilder'. Whenever I run the test file for this particular component, I encounter an error stating that 'FormGroup' an ...

What is a more efficient way to write nested subscribe in Angular?

I am a beginner with RxJS and I'm interested in learning how to write clean code using it. I currently have a nested subscription that I've been trying to refactor without success. firstMethod() { this.testMethod(name) console.log(this.curren ...

Issue with uploading video files using ng2-file-upload in Angular7 and ASP .Net Core 2.1

While working on my project, I encountered an issue with uploading video files using ng2-file-upload to the server. The photo upload functionality is working fine, but when attempting to upload a video file larger than 27MB, the process gets canceled autom ...

Utilizing Angular: Importing Scripts in index.html and Implementing Them in Components

Currently, I am attempting to integrate the Spotify SDK into an Angular application. While I have successfully imported the script from the CDN in index.html, I am encountering difficulties in utilizing it at the component level. It seems like there may be ...

Resolving TypeScript error: Property 'Error' does not exist on type 'Angular2 and Objects'

One of the models I am working with is called "opcionesautocomplete.model.ts" interface IOpcionesAutocomplete { opcionesStyle: OpcionStyle; pcionPropiedades: OpcionPropiedades; } export class OpcionesAutocomplete implements IOpcionesAutocomplet ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

Automatic Form Saving in Angular 4

Seeking to create a form data autosave feature in Angular 4. The functionality should operate as follows: User modifies data in the form -> save request sent to DB. A timer is initiated for 2 seconds. During the 2-second window after the previous s ...

How can esbuild be used to load .wglsl files in Typescript files?

I'm currently utilizing esbuild to bundle my Typescript code, but I'm facing a challenge with configuring a loader for ".wgsl" files. Here is my app.ts file: import shader from './shader.wgsl'; //webgpu logic This is my shader.d.ts fi ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...