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

Convert JSON data to an array using Observable

My current task involves parsing JSON Data from an API and organizing it into separate arrays. The data is structured as follows: [ {"MONTH":9,"YEAR":2015,"SUMAMT":0}, {"MONTH":10,"YEAR":2015,"SUMAMT":11446.5}, {"MONTH":11,"YEAR":2015,"SUMAMT":5392 ...

Utilizing React Typescript to Efficiently Manage Multiple Checkboxes within a List

I'm working on a scenario where I have to manage multiple checkboxes in a list Only one checkbox can be selected at a time For example, if I toggle on Checkbox 1 and then click on Checkbox 2 - I want to automatically toggle off Checkbox 1 as I toggl ...

Saving the compiled Angular dist folder in the artifactory repository

Our team utilizes Artifactory to manage libraries and artifacts. We have configured the npm registry to point to our Artifactory URL for library retrieval. GitLab is integrated into our CI pipeline. Specifically, I have implemented a job that compiles the ...

Generate angular2 a Hashtable containing Strings and Lists

Having trouble printing a HashMap. Last week, I successfully resolved an issue with grouping two fields using Java 8. Now, I am faced with the challenge of printing the response of a project in angular2. The response that I am receiving can be found here ...

The MatTableDataSource provides a promise that includes approximately 7000 rows of data

When attempting to load a large amount of data into a MatTableDataSource, I am facing an issue. I would like to display a loader until the data is fully set, but I am unsure of when that happens. I attempted to use a promise like this: return new Promise(r ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

Using ngForm to implement multiselect options in HTML

Attempting to implement a multiselect dropdown that is tied to a dynamic property receiving data from a JSON script via service. Successfully displayed the data in the dropdown, but encountering abnormalities when adding the multiple attribute within the s ...

Hold off until the observable has finished

map((tasks): any => { return tasks.map(task => ({ ...task, status: this.getStatus(task.owner, task.delegationState, task.assignee, task.id), })); }); I utilize the getStatus method within the map() operator from rxjs. getStatus( ow ...

Is there a method for verifying the application signature in Ionic?

For the past 2 days, I've been on a quest to find information about app certificate validation libraries/functions in Ionic. After discovering SignatureCheck.java for Android (link: enter link description here), I wonder if there is a similar solution ...

Angular 2: Exploring Component Communication with the flexibility of optional input parameters

I am facing a situation where the parent component needs to transmit certain data to a child component using the @Input parameter in Angular. However, this data transfer is not mandatory and the parent may choose whether or not to pass it based on the sp ...

Using Angular's CanDeactivateGuard with Child Components in Angular4

Ensuring user awareness of unsaved changes when navigating away from a page is crucial. Previously, I achieved this in angular 1 using the ng-unsaved changes plugin. However, in angular 4, it seems recommended to utilize the canDeactivate feature. This wor ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

Typesafe-actions for defining typings of async actions reducers

I'm currently facing a minor issue while using createAsyncAction from the library typesafe-actions (Typesafe Actions) and correctly typing them for my reducer function Below is an example of the action being created: export const login = createAsync ...

Incorporating a minute interval in Angular Material's time picker feature

In my Angular 15 project, I am working with this material component. <mat-form-field appearance="outline"> <mat-label>{{'DOCTOR_AREA.START_TIME' | translate}} </mat-label> ...

Remember to store a reference of ViewChild within the parent class

In order to access my graph in a child component using @ViewChild, which is declared in the parent class, I am looking for a way to avoid having to create a new variable for each child class instance. Parent class: import { Component, ViewChild} from &ap ...

Angular6 : PrimeNg datatable: the nova-light theme failing to activate

I'm currently working on an Angular 6 app that is equipped with the latest version of PrimeNG (6.1.4) and I am using a simple datatable component. My goal is to apply the nova-light theme to my datatable, but unfortunately, it is not being applied cor ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

Tips for automatically scrolling the Google Maps view in a React application

After implementing the google-map-react package, I have designed a TypeScript MapView component with the following code snippet. export function MapView<I extends Mappable>({ getData }: MapViewProps<I>): JSX.Element { const [mapZoom, setMapZo ...

Error encountered while attempting to load SWC binary for win32/ia32 in a Next JS application

Upon installing a Next.js app using the command npx create-next-app@latest, I encountered an error while running the app. Can anyone explain why this error occurred and provide a solution? PS D:\New folder\my-app> npm run dev [email pr ...

Converting Objects to Arrays with Angular Observables

After searching extensively on SO for answers regarding item conversions in Javascript/Angular, I couldn't find a solution that addresses my specific problem. When retrieving data from Firestore as an object with potential duplicates, I need to perfor ...