The term "moment" does not have a member called 'default' that can be exported

When attempting to utilize moment.js for changing the local date format in my application, I encountered this error:

The library gives an error stating that "moment" does not have an exported member 'default' when importing.

Here is the code snippet causing the issue:

import {Inject, Injectable, Optional} from '@angular/core';
import {DateAdapter, MAT_DATE_LOCALE, MatDateFormats} from '@angular/material';
import * as _moment from 'moment';
import {default as _rollupMoment, Moment} from 'moment';

const moment = _rollupMoment || _moment;

Answer №1

To resolve the issue, consider including

"allowSyntheticDefaultImports": true
in your tsconfig.json file within the "compilerOptions" section

Answer №2

It appears that you are encountering issues with importing the moment library.

According to the official documentation, If you are using Typescript 2.x, consider adding "moduleResolution": "node" to the compilerOptions in your tsconfig.json file and then use one of the following syntax options:

import * as moment from 'moment';
import moment = require('moment');

Please ensure that you have installed the moment.js library using npm:

npm install --save moment

Answer №3

Below is a comprehensive solution to the problem at hand:

Step One:

 npm install moment --save
 npm install @angular/material-moment-adapter

Step Two:

In your package.json file, ensure you have the following code under dependencies:

    "@angular/material-moment-adapter": "^8.2.3",

Step Three:

Add the following to your tsconfig.json file under compiler options:

"allowSyntheticDefaultImports": true

Step Four:

Update your component with the provided code snippets:

import { MomentDateAdapter } 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: 'YYYY-MM-DD',
  monthYearLabel: 'YYYY',
  dateA11yLabel: 'LL',
  monthYearA11yLabel: 'YYYY',
 },
};

@Component({
 selector: 'app-newsfeedform',
 templateUrl: './newsfeedform.component.html',
 styleUrls: ['./newsfeedform.component.css'],
 providers: [
  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },

  { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
],
})

Step Five:

In your component.html file, include the following code for the datepicker implementation:

     <mat-form-field appearance="outline" fxFlex>
                    <input matInput [matDatepicker]="publishdate" placeholder="Publish Date"
                        formControlName="publishdate">
                    <mat-datepicker-toggle matSuffix [for]="publishdate"></mat-datepicker-toggle>
                    <mat-datepicker #publishdate></mat-datepicker>
                </mat-form-field>

By following these steps, you can easily customize the Angular Material datepicker according to your desired format.

Answer №4

Insert this specific code snippet into the tsconfig.json configuration:

"allowSyntheticDefaultImports": true

Answer №5

To enhance your gulpfile.js, consider including both 'moment/moment' and 'moment' within the externals section.

externals: [
      'moment/moment',
       'moment'
   ]

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

How to apply custom styling to a specific element within an Angular Material 2 component using CSS based on its Id or

My EntryComponent features a material button menu where I attempted to customize the default style using ::ng-deep. However, the changes affected all button components in the parent Component as well. <style> ::ng-deep .mat-button{ max-width: 50 ...

What is the best way to preserve the "window history state" within the current URL?

I am looking to store the "window history state" within the current path, for instance {offset: 10}. This way, when I navigate to a different path and then return using location.back(), I can retrieve the previous path along with the stored state ({offse ...

Using Angular2 moment to format a date in a specific way

Encountered an error while using the amTimeAgo pipe from angular2-moment. The error message is as follows: Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not ...

Experimenting with CDK overlay using Jasmine spy for testing purposes

When it comes to testing cdk overlay, what methods can be used for proper testing? Facing Challenges with MatDialog Service Unit Test in Angular 6 Here is an example of a service call: openNotifications(origin: HTMLElement) { this.refreshNotificatio ...

Ways to display Div contents based on selected options in an Angular 2/4 list

"Struggling with dynamically displaying div contents" Situation:- I have a list of 3 items: *Menu1 *Menu2 *Menu3 and I have separate div contents for each of these menu items. Requirement :- By default, Menu1 should be displayed. When Menu2 is clicked, ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

Best Practice for Using *ngIf in Angular (HTML / TypeScript)

In the past, I frequently used Angular's *ngIf directive in my HTML pages: <p *ngIf="var === true">Test</p> (for instance) However, there have been instances where I needed to perform multiple checks within the *ngIf directive ...

Is there a method to automatically create .stories.ts files in Angular Storybook?

I am seeking a way to automatically create a .stories.ts file within a component folder after executing the command ng g component my-component. The desired outcome should resemble this structure: my-component -my-component.component.html . ...

Using Angular Form Builder to assign a value depending on the selected option in a dropdown menu

My approach to Angular Form Builder initialization includes a group that looks like this: contactReason: this.formBuilder.group({ description: '', source: this.sourceType() }) For the 'description' field, I hav ...

When the button is clicked, I desire to reveal the background color of a specific div

<div class="mat-list-item" *ngIf="authService.isAdmin()" (click)="openModal('site-settings', site.siteID)"> <span class="mat-list-item-content">{{ "Application.site_settings_label&q ...

NgRx not bypassing the 'successful' action when encountering an error

I am encountering an issue with the following effect: updateBook$ = createEffect(() => this._actions$.pipe( ofType(START_UPDATE_BOOK), exhaustMap(action => this._api.updateBook({id: action.id}).pipe( map(data => UPDATE_B ...

"Experience the seamless navigation features of React Navigation V6 in conjunction with

Hello there, I've been experimenting with react-navigation 6 in an attempt to show a modal with presentation: "modal" as instructed on the documentation. However, I'm facing an issue where the modal is not displaying correctly and appears like a ...

The functionality to dynamically adjust the number of items displayed per slide on the Carousel component in ngx-bootstrap is currently not available

I am attempting to dynamically change the number of items displayed on a carousel during runtime. The purpose of this is to optimize viewing for users on small devices such as smartphones. My intention is to have only 2 items per slide when viewed on a s ...

exploring asynchronous javascript behavior utilizing the sleep/setTimeout function in the context of THREEJS and Angular

As a newcomer to Javascript and asynchronous programming, I am facing what I believe to be a beginner's issue. I have been using ThreeJS to create a scene with multiple objects (approximately 100) and everything was working smoothly until now. My cu ...

What makes it impossible to use var instead of let in ngFor?

My understanding is that in JavaScript, we typically use var and let for variable declarations. The main difference between the two is that var is scoped to the current function, while let is scoped to the current block. Therefore, theoretically I should b ...

Is it possible to utilize the $ symbol within the ngOnInit or constructor functions?

I recently encountered an issue while trying to use the dollar sign ($) in my constructor function, specifically within ngOnInit() and translate.instant. Here is a snippet of the code that caused the problem: declare var $: any; { var SelectedDevice = ...

What is the recommended approach in Angular for unassigned @Input() variables when using TypeScript strict mode?

Issue at Hand After upgrading my Angular version from 10 to 13, I encountered a problem with the new TypeScript strict compiler mode. The upgrade required me to assign values to all declared variables upon initialization, causing issues with properties de ...

Steps to globally modify the font in Ionic

In my Ionic app running version 3.9.2, I am attempting to customize the default font to a specific custom one. After researching, I discovered that I need to set the font face in the app.scss file located within the app folder. Here is the code snippet I ...

What to do when faced with the Netlify Error "Dependency Installation Failure"?

Having trouble deploying a website created with react and typescript. I keep encountering an error during the initialization phase: https://i.sstatic.net/LNhFJ.png https://i.sstatic.net/w7KTo.png This is all new to me as I just started working with react ...

Problem with Angular 5: Data Binding Issue未知EncodingException

Struggling to understand... I want to make a GET request to my service to retrieve the specific hardware associated with the barcode I scanned - this part is working correctly. The hardware information is returned as an object that looks like this -> ...