The Angular Material DatePicker fails to update in accordance with the Moment locale settings

Issue: Inconsistency with Angular Material 7 DatePicker and moment js integration

Challenge: The datepickers fail to update their locale when the language of the web application is changed.

Objective: I aim to have my date pickers automatically adjust to the selected language's format whenever a change in language occurs within my application. Currently, I find myself switching between dd/MM/yyyy and MM/dd/yyyy manually.

Seeking Guidance: As a newcomer to moment, I'm struggling to implement the necessary formatting adjustments. Any helpful pointers would be greatly appreciated.

Sample HTML code:

<mat-form-field>
  <mat-label>From date</mat-label>
  <input name="fromDate" [min]="minDate" [max]="maxDate" [formControl]="displayFromDate" 
                     matInput [matDatepicker]="fromDatePicker">
  <mat-datepicker-toggle matSuffix [for]="fromDatePicker"></mat-datepicker-toggle>
  <mat-datepicker #fromDatePicker disabled="false"></mat-datepicker>
</mat-form-field>

Snippet from translation service that switches moment locale based on language selection: The 'lang' parameter toggles between 'en' and 'fr', controlled by an app switch.

public use(lang: string): void {
  this._currentLang = lang;
  moment.locale(lang);      
  this.currentLang$.next(this.currentLang);
}

App.module.ts excerpt:

import { MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter';

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

import localeFr from '@angular/common/locales/fr';
import localeEn from '@angular/common/locales/en';

registerLocaleData(localeFr);
registerLocaleData(localeEn);

...

imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,

...

{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS },],

Component snippet utilizing the datepicker:

this.translationService.currentLang$.subscribe(currentLang => {      
  this.displayFromDate = new FormControl({ value: moment(this.displayFromDate.value).format(), disabled: true });
  console.log('displayFromDate', this.displayFromDate);
});

Answer №1

After going through the angular documentation I realized that setting the locale requires using the data adapter. For those who may be searching for this information, ensure you utilize the data adapter to specify your desired locale.

constructor(private adapter: DateAdapter<any>) {}

toggleLocale() {
  this.adapter.setLocale(moment.locale());
}

Answer №2

For determining the user's timezone, you can use moment.tz.guess() function along with an optional boolean parameter called "ignoreCache". When this parameter is set to true, the cache will be disregarded and updated with the new value.

More information can be found in the Moment documentation at this link.

To see a live example of this in action, check out this demo: here.

Answer №3

My solution to all datetime issues was straightforward:

Uninstalled moment package
Removed @angular/material-moment-adapter
Installed @angular/material-luxon-adapter

Inside app.module.ts:

import { LuxonDateAdapter, MAT_LUXON_DATE_ADAPTER_OPTIONS, MAT_LUXON_DATE_FORMATS } from '@angular/material-luxon-adapter';

providers: [
     {provide: MAT_DATE_LOCALE, useValue: 'default'},
     {provide: DateAdapter, useClass: LuxonDateAdapter, deps: [MAT_DATE_LOCALE, MAT_LUXON_DATE_ADAPTER_OPTIONS]},
     {provide: MAT_DATE_FORMATS, useValue: MAT_LUXON_DATE_FORMATS}
    ]

Don't forget to update chrome://settings/languages for testing purposes.

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

Using TypeScript to separate namespaces

tsconfig.json: ... "module": "none" ... file1.ts: namespace Myns { type Mytype = number } file2.ts: namespace Myns { let x: Mytype ^^^^^^ Error - unable to locate declaration in file1.ts } Why am I encountering an error when trying to us ...

Importing Heroicons dynamically in Next.js for more flexibility

In my Next.js project, I decided to use heroicons but faced a challenge with dynamic imports. The current version does not support passing the icon name directly to the component, so I created my own workaround. // HeroIcon.tsx import * as SolidIcons from ...

Tips for saving an Angular project for offline use

I have created a basic form for a family member to use in their medical practice, and I want to make it functional offline. The form simply captures data and displays it, with no need to send or store the information anywhere. What would be the most effect ...

Refreshing a paginated mat-table in Angular results in missing row data

My mat-table is designed to fetch data from firebase. AllMatchesComponent.html ... <mat-table #table [dataSource]="dataSource" class="mat-elevation-z8"> ... <ng-container matColumnDef="rank"> <mat-header-cell *matHeaderCellDe ...

No output returned by SwitchMap in Angular 2

I'm facing an issue with my SwitchMap implementation and struggling to resolve it. The problem occurs when I have a collection of category buttons that, when clicked, trigger a server call to load the corresponding data. However, if I switch between t ...

Unable to log out of OIDC-client due to an error: end session endpoint not found

Currently, I am in the process of setting up a code flow with Auth0 as my chosen identity provider. Successfully, the sign-in process functions well and I receive a valid token from Auth0. However, I am encountering an issue when attempting to sign out ...

Injecting a service into a base class in Angular/TypeScript without injecting it into a sub-class

I am working with a basic ServiceBase class that has Http injected into its constructor: import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; export abstract class ServiceBase<T> { constructor ...

Whenever I choose an ionic tab that has a changing URL, the tab does not appear as highlighted

My issue involves the ion tab setup in tabs.page.html. The user_id is set in the tabs.page.ts file within the same directory, ruling out any issues there. <ion-tabs> <ion-tab-bar slot="bottom"> ... <ion-tab-button tab=“profil ...

Discover additional features in Angular 4 by reading further

I am struggling with incorporating a "read more" feature in my paragraph on my website. The challenge I'm facing is determining how to trigger the feature to display only when there are more than 5 lines of text. <p>Contrary to popular belief, ...

Prevent additional functions from running when clicking in Angular 5

I have implemented an Angular material table where each row expands when clicked. In the last cell of the table, I load a component dynamically using ComponentFactory. This loaded component is a dropdown menu. The problem arises when the dropdown menu is ...

Ensuring input validity within an ngFor loop utilizing template-driven forms

Within our Angular form (utilizing template driven forms), there exists a dynamic list of input fields that require validation. Despite consulting Using template driven form with dynamic input list (ngFor), the provided information seems to be outdated, as ...

The highcharts-angular version of the stock-tools-gui demo is lacking a graphical user interface (GUI)

Attempting to create an Angular version of this impressive demo: https://www.highcharts.com/stock/demo/stock-tools-gui . Utilizing the highcharts-angular wrapper in this project: https://codesandbox.io/s/pjkqwwmkr7 - everything is functional except for t ...

I wonder, who is the one executing the function?

In my application, I have encountered an unusual issue. Within my controller, I have two functions - one to add a tab, and one to remove a tab. Below is the code snippet: $scope.createTab = function(){ $scope.addTab("New Tab",50,0); co ...

What is the best way to add prefixes to my SCSS style sheets?

After attempting to add prefixes to my scss files, I came across the autoprefixer tool. However, I discovered that it only supports CSS files. Is there a way to utilize autoprefixer with scss files? Here are the commands for Autoprefixer: npm install post ...

Eliminate using a confirmation popup

My attempts to delete an employee with a confirmation dialog are not successful. I have already implemented a splice method in my service code. The delete function was functioning correctly before adding the confirmation feature, but now that I have upgrad ...

Avoid displaying the value in Ant Design's autocomplete feature

Can someone assist me with clearing the auto complete placeholder or displaying only part of the label instead of the value after a user selects from a drop-down list? The current setup shows the unique ID as the value, which we want to keep hidden from en ...

Tips for successfully transferring a JsonifyObject<T> from Remix's useLoaderData<typeof loader> to a function

Encountering a TypeScript error while trying to import JsonifyObject in the Remix 2.9.2 route code below... Argument of type 'JsonifyObject<IdAndDate>' is not assignable to parameter of type 'IdAndDate'. Struggling to figure ou ...

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...

Developing and employing Services in Angular 2

Having some trouble with Angular2 as I explore it for the first time, specifically in creating and using a service. I've set up a data service like this: import {Injectable} from 'angular2/core'; import {recentActivity} from './app/com ...

Utilizing server-side caching middleware with tRPC version 10

Currently, I am working on a Next.js project and exploring the possibility of incorporating in-memory caching for tRPC results. Each tRPC procedure should have the option to set a custom TTL for caching purposes. My initial thought is that utilizing tRPC&a ...