What could be causing the Moment function to return the error message 'not a function'?

I encountered an issue where my code works perfectly in localhost but fails in production, displaying the error

ERROR TypeError: n.endOf is not a function

import * as moment from 'moment';

changeMaxDate(maxTime: moment.Moment) {
    if (maxTime) {
        return maxTime.endOf('day').toISOString();
    }
}

Despite extensive research on Moment questions and documentation, I have been unable to find a solution.

I have attempted various approaches, including using import moment from 'moment'; which also did not resolve the issue

Using Moment.js 2.24.0

TypeScript version 3.5.3

Angular version 8.2.3

<input matInput
                   [matDatepicker]="maxTime"
                   [(ngModel)]="data.maxTime"
                   (ngModelChange)="changeMaxDate(data.maxTime)"
                   placeholder="{{ 'yyyy-mm-dd' | translate }}">
    <mat-datepicker-toggle matSuffix [for]="maxTime"></mat-datepicker-toggle>
    <mat-datepicker #maxTime></mat-datepicker>

The maxTime extracted from the datepicker in localhost successfully displayed the Moment object:

Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…},                     
_locale: Locale, …}
_d: Mon Nov 04 2019 23:59:59 GMT+0100 (Central European Standard Time)
__proto__: Object
_i: {year: 2019, month: 10, date: 4}
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate:                 "Invalid date", _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …}
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0),     overflow: -1, charsLeftOver: 0, …}
__proto__: Object

However, in the production environment, it was converted into a string value:

Mon Nov 04 2019 00:00:00 GMT+0100 (Central European Standard Time)

Answer №1

Which specific data are you providing as a parameter? In this scenario, it appears that moment.Moment is considered to be of the type any. Consequently, the if statement if (maxTime) will evaluate to true even with an empty object {} or Date being passed. However, these objects do not feature the endOf function.

You could approach it in the following manner:

changeMaxDate(maxTime: moment.Moment) {
    if (maxTime && typeof maxTime.endOf === 'function') {
        return maxTime.endOf('day').toISOString();
    }
}

Answer №2

To incorporate moment with matDatepicker in your Angular application, make sure to include the MomentDateAdapter in the providers section of your app.module.

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

Don't forget to import these modules from @angular/material.

Answer №3

If you're using both [(ngModel)] and (ngModelChange) simultaneously, it may not work as expected because [(ngModel)] is already handling changes. Check out this link for more information: https://angular.io/guide/template-syntax#two-way-binding- Also, the output format of your function seems to be incorrect.

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

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

Exploring mysterious traits through inheritance

In my Angular and TypeScript project, I have defined an interface: export interface A { name: string; } Now I have two other interfaces that inherit from interface A: export interface B extends A { year: number; } export interface C extends A { ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

After updating the Angular template, I encountered an unexpected error

Upon executing ng update and then running ng serve, I encountered the following error: ERROR in node_modules/@agm/core/services/maps-api-loader/lazy-maps-api-loader.d.ts(1,10): error TS2305: Module '"/home/maroodb/WebstormProjects/user-dashboard-ng/n ...

Ways to display dynamic information in a vertical list using HTML (MEAN stack)

I am receiving an array of data from the backend and looking for a way to display them in a vertical list using HTML. Can anyone help me with this? Below is my current code snippet. TS: this.sub = this.route.params.subscribe(params => { this.http.g ...

Event emitters from Angular 4 are failing to receive emitted events after the page is refreshed

Hey there, I'm facing an unusual issue with event emitters not functioning correctly during page refreshes. Here's the scenario: First, the user lands on the login page. Upon successful login, they are directed to the home page where I need spec ...

Unable to subscribe to mergeMap observable in Angular 13

I am currently working on implementing a connection scenario in Angular that is based on user roles. When the user clicks on the "CONNEXION" button after filling out the form with their username and password, two API URLs are triggered to facilitate the sa ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Enter the Angular Date Picker on Safari

While working with Angular and ngx-bootstrap, I encountered an issue where the input type=date does not function properly on Safari Browser. Can anyone suggest a solution to fix this problem? ...

Combine JavaScript code with its corresponding TypeScript definition located in separate files

I am trying to utilize a specific file from a repository without the need to install its NPM package. This particular file was written in JavaScript and has a separate definition file. The JavaScript file contains an export for the Headers class. The Type ...

Adjusting the height of an Angular CDK virtual scroll viewport based on dynamic needs

Currently, I am developing an Angular table with the cdk Virtual Scroll feature. Is there a method to adjust the scroll viewport's height dynamically? While the standard style property works, I am encountering difficulties setting the value using ngSt ...

Encountering an issue within the directive.spec.ts file in Angular

Within my code, I have developed a custom directive named changeText, which is implemented in the file change-text.directive.spec.ts. However, an error arises when I try to instantiate it using const directive = new ChangeTextDirective(); change-text.dir ...

Unusual encounters within arrays

Can anyone offer some assistance with this issue? getPositionsPortfolioUpdated(){ this.positionsWholeAccUpdated = []; this.positionsWholeAccUpdated = this.allPositionsFromAllAccs this.positionsWholeAccUpdated.forEach((pos, index) => { ...

Exploring the creation of dynamic reactive forms with patterns generated by an API

I'm working on an Angular form group with an input field for an email address, and I need to add regex patterns for the domain extension based on what's in my database. The getAllDomain service call is already set up. However, I am unsure of ho ...

Guide on verifying if a variable is a tuple in TypeScript

I am attempting to determine if a variable passed to a function, which can either be an array of numbers or an array of tuples, is the array of tuples. function (times: Array<number> | Array<[number, number]>) { if (Array.isArray(times[0]) ...

Dealing with arrays in Typescript and flattening them using the RX

Struggling with a problem involving RXJS transformation in an Ionic 2 application. My goal is to flatten a JSON file into objects, here is the simplified JSON structure: [{ "language": "it", "labels": { "name": "Hi", }, "t ...

Separating Angular code into distinct components

My page contains two input fields: one is for email and the other is a text field. Currently, everything is functioning correctly. However, I now want to split the component into two parts. For example, I have a 'basic-info' component currently. ...

Issue: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]:

While I am going through a tutorial on the abp framework, I encountered an error with the Author route that says "ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelp ...

Is it possible to perform sorting and searching of data directly on the client side using AG-Grid?

We have set up an API in .NET Core C# to retrieve data and display it in a grid using AG Grid in Angular. Our API incorporates server-side pagination for efficient data loading. Next, I am looking to add client-side sorting and searching functionalities t ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...