Angular Material Datepicker: Changing the input field format when the field value is updated

Currently, I am utilizing a mat-date-rang-input component from Angular Material. To customize the date format to dd/MM/yyyy, I made adjustments within Angular Material which is functioning correctly.

<mat-form-field ngClass="filters_dateInterval">
    <mat-label>Date interval</mat-label>
    <mat-date-range-input [rangePicker]="picker" md-date-locale="{
                  inputDisplay: dd/MM/yyyy
                }}">
        <input matStartDate placeholder="Start" [(ngModel)]="dateStartFilterField" (valueChanges)="show($event)" />
        <input matEndDate placeholder="End" [(ngModel)]="dateEndFilterField" />
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="picker" ngClass="filters_dateInterval__icon"></mat-datepicker-toggle>
    <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

However, during my test of the user interface/user experience (ui/ux), I observed an unexpected behavior. Upon entering a date in the format dd/MM/yyyy and moving focus away, the format would revert back to MM/dd/yyyy.

To address this issue, I attempted modifying the app.module.ts file by adding a provider for date formatting.

providers: [
    {
      provide: LOCALE_ID,
      useValue: DATE_FORMAT_PTBR
    }
]

This is how I defined the DATE_FORMAT_PTBR:

export const DATE_FORMAT_PTBR = {
  parse: {
    dateInput: 'dd/MM/yyyy',
  },
  display: {
    dateInput: 'dd/MM/yyyy',
    monthYearLabel: 'MMMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY'
  },
  formater: {
    dateInput: 'dd/MM/yyyy',
  }
};

I also tried changing the value of useValue to 'pt-BR' in providers, but unfortunately, it did not resolve the issue.

Answer №1

Here is the corrected TS file:

import { MAT_DATE_FORMATS } from '@angular/material/core';

export const MY_DATE_FORMATS = {
    parse: {
      dateInput: 'DD/MM/YYYY',
    },
    display: {
      dateInput: 'DD/MM/YYYY',
      monthYearLabel: 'MMMM YYYY',
      dateA11yLabel: 'LL',
      monthYearA11yLabel: 'MMMM YYYY'
    },
};


 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS }
  ]
})

And here is the corrected HTML file:

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker ></mat-datepicker>
</mat-form-field>

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

Refining Typescript type with specific error for generics

Seeking assistance to comprehend the situation: TS playground The situation involves a store with an exec method, where narrowing down the type of exec param is crucial for a sub process. However, an error seems to arise due to the store type being generi ...

The journey of an Angular and NGXS store application culminates in a seamless loop of store updates

Currently, I am utilizing NGXS as the store mechanism in my application. Within the store, there is a list of conditions that are displayed using the RuleEngineAddViewStepperConditionComponent component and the *ngFor directive on the UI. Each condition ha ...

Taking out the modal element from the document object model, causing the animation

I am currently working on a project using Next.js, Typescript, and Tailwind CSS. Within this project, I have implemented a modal component with some animations. However, I encountered an issue where the modal does not get removed from the DOM when closed, ...

What is the most efficient way to retrieve a single type from a union that consists of either a single type or an array of types

Is there a way to determine the type of an exported union type by extracting it from an array, as illustrated in the example above? How can this be achieved without directly referencing the non-exported Type itself? interface CurrentType { a: string; b ...

Exploring the functionalities of TypeScript's mapKey and pick features

I am looking to convert the JavaScript code shown below into TypeScript, but I don't want to use loadish.js. let claimNames = _.filter<string>(_.keys(decodedToken), o => o.startsWith(ns) ); let claims = <any>( _.mapKeys(_ ...

"Alert: The ToastData is nowhere to be found in

In my previous Angular 5 application, I was using ng2-Toasty for displaying toasts. However, since ng2-Toasty does not support Angular 8, I am now trying to switch to ngx-toastr. Upon implementation, I noticed that ngx-toastr does not have an equivalent o ...

I am unable to add a new property to the request object in the Express framework

My goal is to add a new property to the request object in typescript. Here's the code snippet I'm using: import { request, Request, response, Response } from "express"; ((req: Request, res: Response) => { console.log(req.user); ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Unable to bring in a personalized npm package using its package title

Currently, I am loosely following a tutorial on creating an angular npm package named customlib. This package is intended for managing dependencies across my projects without the need to make them public on npm. The tutorial can be found here. However, I ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

I encountered TS2300 error stating a duplicate identifier appeared once I transferred my code to Angular CLI

Currently undergoing the process of transitioning our code to Angular CLI for our hybrid app. The plan is to migrate the Angular part to CLI while the AngularJS portion continues to be handled by custom Webpack. It's worth noting that both parts (Angu ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

Interacting between two Angular 4 applications

I came across solutions here and here related to this issue, but they seem to be for an older beta version of Angular (I believe now we should bootstrap a module, not a component; also, I couldn't find the bootstrap function in the documentation for v ...

Struggling to incorporate generics into a Typescript method without sacrificing the typing of object keys

Currently, I am working on a method in Typescript that is responsible for extracting allowable property types from an object of a constrained generic type. The scenario involves a type called ParticipantBase which consists of properties like first: string ...

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

What could be causing the 404 error when trying to make a get-request to fetch a list of all users?

Having trouble retrieving a list of users using my endpoint, as it keeps returning a 404 error. I have set up a model, controller, router, and index file for the user in my application. Below is the User.ts model: import { Schema } from 'mongoose&apo ...

Implementing computed properties: A guide to incorporating type setting

I currently have two separate interfaces defined for Person and Dog. interface Person { name: string; weight: number; } interface Dog { name: string; mass: number } const specificAttribute = isDog ? 'mass' : 'weight'; ...