Inputting Dates Manually in the Angular Material Datepicker Field

The datepicker function works well unless I manually type in the date. When I input a date between 01.MM.YYYY and 12.MM.YYYY, the value switches to MM.DD.YYYY. However, if I input 16.09.2021 for example, it remains as DD.MM.YYYY.

Is there a way to change the date format from the input field?

HTML

<div class="form-group inline datepicker">
  <mat-form-field appearance="fill">
      <input matInput
             [matDatepicker]="validFromPicker"
             [formControl]="validFromFormControl"
             (dateChange)="setValidFromDate($event.value)">
      <mat-datepicker-toggle matSuffix [for]="validFromPicker"></mat-datepicker-toggle>
      <mat-datepicker #validFromPicker></mat-datepicker>
  </mat-form-field>
</div>

TypeScript

 validFrom: Date;
 validFromFormControl: FormControl;
 
 ngOnInit() {
   this.validFromFormControl = new FormControl(new Date());
   this.validFrom = new Date();
 }

 setValidFromDate($event: any) {
   this.validFrom = $event;
 }

I attempted to adjust the locale in AppModule following advice from this thread - , but unfortunately, it did not work as expected.

Answer №1

To easily change the locale, utilize the MomentDateAdapter:

providers: [
// The locale is usually provided on the root module of your application. In this example, it is done at
// the component level due to limitations of our example generation script.
{ provide: MAT_DATE_LOCALE, useValue: 'en-US' },

// Importing `MatMomentDateModule` in your application's root module can automatically provide
// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS`. We are providing it at the component level
// here due to restrictions of our example generation script.
{
  provide: DateAdapter,
  useClass: MomentDateAdapter,
  deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }]

For a complete code illustration, check out this stackblitz example.

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

Every time I hit the refresh button, I receive dual responses

In my angular 6 application, there's a sidebar component sidebar.ts ngOnInit() { if (!Array.isArray(this.menu) || !this.menu.length) { const data = JSON.parse(localStorage.getItem('data')); this.item = data.response; ...

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

Global Enum in Typescript that is Optimized for Inlining during Compilation

I'm facing a challenge with an enum that is widely used in my project. Having to import it into every file is becoming cumbersome. Is there a way to define the enum in the .d.ts file so that it automatically gets included when compiled to Javascript? ...

Resolving circular dependencies caused by APP_INITIALIZER

My AuthenticationService is responsible for loading the AngularFirestore and is loaded in the RootComponent. All app modules are lazily loaded within the RootComponent (which contains the main router-outlet). However, several sub-modules also load the Ang ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

Enhance Typescript with Extension Traits

Picture this scenario: You have a class A with a method that can create an instance of class B. You're unable to make any changes to the code of either A or B, as they are part of an external library. In this situation, if you want to enhance the fun ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

Material-UI: Tips for aligning pagination button in the center

My attempt to implement Pagination using Material-UI went well, but now I am struggling to center the arrow buttons and page numbers. I initially tried centering them by wrapping them in a <div style={{textAlign: "center"}}>, however this ...

Best practices for using useEffect to fetch data from an API_FETCH in a certain condition

When retrieving state from an API using Zustand within a useEffect function, what is the recommended approach to do so? Currently, my implementation is quite straightforward: export interface ModeState{ modes: Mode[]; fetchModes: () => void; } expo ...

I tried implementing enums in my Angular Material select component, but unfortunately, it seems to be malfunctioning

Here is my TypeScript file I am working on creating a select list with enums in my project, but I am encountering an error. I have shared screenshots showing the enums with both keys and values, but I only want to display their keys and save their values ...

Difficulties with Geolocation Installation

Encountering an issue while trying to set up Geolocation in my ionic App, I continuously receive the error message below. Is there anyone who can offer assistance? npm ERR! code E405 npm ERR! 405 Method Not Allowed - GET https://registry.npmjs.org/@ionic ...

How to access NavController in an Ionic2 service provider

In my Ionic2 app, I have created an AuthHttpProvider which acts as a wrapper for Http requests and automatically adds an authentication token (jwt) to each request. I use this instead of the default Http provider in all of my interactions with the server. ...

How can I utilize a variable as the value for ngClass in Angular 2?

Is there a way to use a variable in the ngClass value that gets added to the class list? I have a scenario where I have a set of image sprites, including a base sprite and an active state sprite with "-active" appended to the filename. I insert these sprit ...

Show the chosen choice in a select dropdown with custom text using Angular

I successfully implemented this code snippet to display a dropdown list of countries and their phone codes. However, I encountered an issue where I need to only show the selected option's code without the country name. The first screenshot shows how i ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

An issue occurred: The module failed to self-register at the specified path: '/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/onnxruntime_binding.node'

Hey there, I'm trying to implement transformer js in my node js application using typescript. The code is located in a file named worker.js. const TransformersApi = Function('return import("@xenova/transformers")')(); const { CLIPVisionModel ...

The Conundrum of Angular 5 Circular Dependencies

I've been working on a project that involves circular dependencies between its models. After reading through this StackOverflow post and its suggested solutions, I realized that my scenario might not fit into the category of mixed concerns often assoc ...

Is it possible to pass a prop from a parent container to children without knowing their identities?

I am currently working on a collapsible container component that can be reused for different sections of a form to display fields or a summary. Each container would include a Form object passed as a child. Here is the basic structure of my code: function C ...

Adding dynamic row values to a bootstrap table in angular 4 - what's the best approach?

When using an Angular 4 bootstrap table, I am encountering an issue where only the first row value is displayed in the table from the backend when entering a product in the text box and pressing enter. Even though the alert window shows the data for the se ...

What is the solution to prevent angular-material components from covering my fixed navbar?

After creating a navbar using regular CSS3, I incorporated input fields and buttons from angular material. However, my sticky navbar is being obscured by the components created with angular material. Here is the CSS for the navbar: position: sticky; top: ...