Changing the Date Format in Reactive Forms: A Guide

I need to update the date format displayed in my field within Reactive forms. Currently, it shows as "16-03-1999" but I want it to display as "March 16, 1999."

Here is the relevant code:

In my TypeScript file:

this.companyForms = this.fb.group({

})

I am dynamically adding a control to the form using API response:

this.companyForms.addControl("EFFECTIVE_DATE", new FormGroup({
        'DEFAULT VALUE': new FormControl(null)
}))

In the HTML file:

<form [formGroup]="companyForms">
   <div class="row pt-2" formGroupName="EFFECTIVE_DATE">
      <input type="date" class="form-control bg-light" name="DEFAULT VALUE" formControlName="DEFAULT VALUE" [value]="companyForms.get(['EFFECTIVE_DATE','DEFAULT VALUE'])| date:'longDate' ">
   </div>
</form>

While attempting to use the built-in pipe longDate to change the date format, it still displays as 'dd-mm-yyyy'. I want it in "mmmm dd, yyyy" (June 26, 2019) format.

The placeholder for the date field continues to show the default format of dd-mm-yyyy.

If anyone has suggestions on how to achieve the desired format, your input would be greatly appreciated. Thank you!

Answer №1

If you want to implement a datepicker in Angular, Angular Material is a great option to consider. Here is an example of how you can use Angular Material to create a datepicker:

<mat-form-field appearance="fill">
  <mat-label>datepicker</mat-label>
  <input matInput [matDatepicker]="dp" [formControl]="date">
  <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
  <mat-datepicker #dp></mat-datepicker>
</mat-form-field>

Additionally, here is the TypeScript code required for this functionality:

import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import * as _moment from 'moment';
import {default as _rollupMoment} from 'moment';

const moment = _rollupMoment || _moment;
export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'LL',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};
@Component({
  selector: 'datepicker-formats-example',
  templateUrl: 'datepicker-formats-example.html',
  providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
export class DatepickerFormatsExample {
  date = new FormControl(moment());
}

You can view a demo of this implementation on StackBlitz.

Answer №2

ng-bootstrap offers a convenient ngb-datepicker component that can be used in place of a standard input field. An example of how to format the date for this component can be found in the official documentation: custom date formatter.

Here is the code for the custom date parser formatter:

@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {

  readonly DELIMITER = '/';

  parse(value: string): NgbDateStruct | null {
    if (value) {
      let date = value.split(this.DELIMITER);
      return {
        day : parseInt(date[0], 10),
        month : parseInt(date[1], 10),
        year : parseInt(date[2], 10)
      };
    }
    return null;
  }

  format(date: NgbDateStruct | null): string {
    return date ? date.day + this.DELIMITER + date.month + this.DELIMITER + date.year : '';
  }
}

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 properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Do I still need to install react-router if I have already installed @types/react-router?

My React project was initiated using create-react-app create-react-app my-app --scripts-version=react-scripts-ts Upon creation, the package.json file contained the following: { "name": "my-app", "version": "0.1.0", "private": true, "dependencies ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

The base URL specified in the tsconfig file is causing the absolute path to malfunction

Displayed below is the layout of my folders on the left, along with a metro error in the terminal and my tsconfig.json configuration with baseUrl set to './src'. Additionally, I have included screenshots of my app.ts and MainTabs.ts for further c ...

Use the date-fns max function to identify the latest date in an array of date strings

The Dates string array is created using data from the backend object in the following manner: const dates: string[] = this.data.map((item:any) => item.date.jsdate); Here is the resulting array: dates = [ Thu Jan 12 2015 00:00:00 GMT+0530 (India T ...

AngularJS 2 TypeScript structure

My application includes a user service for managing user operations and an interface for the user object. user.service.ts import {Injectable} from 'angular2/core'; export interface User { name: string; email?: string; picture?: string; } ...

Creating a bootstrap carousel configuration

I recently encountered a problem while using a single bootstrap carousel. The carousel contains multiple items/images to display, with one of them needing to be active initially. Below is the code snippet: <div id="myCarousel" class="caro ...

Discovering action creator names using auto-complete in a React component: A step-by-step guide

Lately, I've been using React and Redux with TypeScript and it's been an amazing experience. One great thing is that I can easily access my store state using useAppSelector, as specified in the official React-Redux documentation. This feature ha ...

What is the connection between @types, TypeScript, and Webpack?

When using an exported type in a .ts file, it is necessary to import it: import {jQuery} from 'jQuery' Even after adding the import, intellisense may not work until npm install @types\jQuery is executed. If @types are installed, intellis ...

Having issues with matSort functionality on mat-table in Angular

The content of my .html file is shown below: <mat-table [dataSource]="dataSource" padding matSort> <ng-container matColumnDef="uid"> <mat-header-cell *matHeaderCellDef mat-sort-header> Building UID </mat-header-cell&g ...

Angular2 Window Opener

Trying to establish communication between a child window and parent window in Angular 2, but I'm stuck on how to utilize window.opener for passing a parameter to Angular 2. In my previous experience with Angular 1.5, I referenced something similar he ...

Firebase is storing object values as 'undefined'

My goal is to retrieve user details from my firebase database while using Ionic and Typescript. Here is how I add a user: addToDatabase(user: User) { let isInstructor = user.isInstructor == null ? false : user.isInstructor; this.afDB.list("/users/").push ...

How to execute an object function in TypeScript only if it is defined

Currently, I am working on creating a binary search tree class in Typescript as part of my learning journey with the language. My aim is to incorporate generics into this exercise. In the process of implementing algorithms within the class, I have encount ...

Obtain a collection of custom objects through an HTTP GET request to be utilized in an Angular 2 application

I am currently grappling with the task of efficiently retrieving a list of custom objects and displaying their contents using an HTML file. Here is a simplified version of the HTTP GET method that I am working with: [HttpGet("/atr/testing")] public List& ...

Testing a component in Angular 2 that utilizes the router-outlet functionality

I recently set up an angular 2 project using angular-cli. As part of the setup, I created a separate AppRoutingModule that exports RouterModule and added it to the imports array in AppModule. Additionally, I have the appComponent which was generated by an ...

The issue with the overlay not being properly shown in the Angular Material menu

After following the instructions from here to connect the menu component, I noticed that the body of the menu is simply inserted into the document's body and does not resemble a modal window. https://i.stack.imgur.com/47wlj.png The dependencies list ...

Leveraging TypeScript to call controller functions from a directive in AngularJS using the "controller as"

I've encountered an issue while trying to call a controller function from a directive, specifically dealing with the "this" context problem. The logService becomes inaccessible when the function is triggered by the directive. Below is the code for th ...

Typescript function incorrectly returns Protractor's "element.all" output as Promise<string> instead of Promise<string[]>

Kindly review the code snippet provided below. The function getAllGroupIds() is designed to return an array of IDs belonging to "group" elements. The goal is to retrieve all the group-ids both before and after a test action, in order to compare them. Howe ...

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? ...

Retrieve information from an XML document

I have some XML content that looks like this: <Artificial name="Artifical name"> <Machine> <MachineEnvironment uri="environment" /> </Machine> <Mobile>taken phone, test when r1 100m ...