Tips on updating the datepicker format to be dd/mm/yyyy in ngbdatepicker

I am currently using ng-bootstrap for a datepicker and need to change the date format from yyyy/mm/dd to dd/mm/yyyy. I have tried to make this adjustment but haven't had success. If anyone has suggestions on how to accomplish this, please help.

Here is a demo of my current implementation: https://stackblitz.com/edit/angular-6wpn3h-ahcq4x?file=src/app/datepicker-popup.html

  <div class="input-group">
  <input class="form-control" placeholder="dd/mm/yyyy"
         name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">
  <div class="input-group-append">
    <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
  </div>
  </div>

Answer №1

To create a custom date formatter using ng-bootstrap's NgbDateISOParserFormatter as inspiration, you can follow the approach below in datepicker-popup.ts. This code simplifies the formatting process and eliminates the need to import util.ts:

import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';

function padNumber(value: number | null) {
  if (!isNaN(value) && value !== null) {
    return `0${value}`.slice(-2);
  } else {
    return '';
  }
}

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct | null {
    if (value) {
      const dateParts = value.trim().split('/');

      let dateObj: NgbDateStruct = { day: <any>null, month: <any>null, year: <any>null }
      const dateLabels = Object.keys(dateObj);

      dateParts.forEach((datePart, idx) => {
        dateObj[dateLabels[idx]] = parseInt(datePart, 10) || <any>null;
      });
      return dateObj;
    }
    return null;
  }

  format(date: NgbDateStruct | null): string {
    return date ?
        `${padNumber(date.day)}/${padNumber(date.month)}/${date.year || ''}` :
        '';
  }
}

After creating NgbDateCustomParserFormatter, remember to import it and set the provider in @NgModule within datepicker-popup.module.ts:

providers: [
    {provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
   ]

I have included this implementation in your StackBlitz project for reference here.

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

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for ...

Streamline imports with Typescript

Is there a way to import modules with an alias? For example, I have an angular service in the folder common/services/logger/logger.ts. How can I make the import look like import {Logger} from "services" where "services" contains all my services? I've ...

Error in custom TypeScript: Incorrect error instance detected within the component

I encountered a unique issue with my custom Error export class CustomError extends Error{ constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); this.name = "CustomError"; } Furthermore ...

Troubleshooting: Issues with Angular2 compatibility on Safari version 9.1.2

I am encountering an issue with running my angular2 app on Safari 9.1.2. It works fine on all higher versions of Safari as well as other browsers such as Chrome, Firefox, Opera, and Edge. However, when I try to run it on Safari 9.1.2, I receive the followi ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

How to designate a try / catch block as asynchronous in TypeScript / JavaScript?

I am facing an issue where the code is not entering the catch block in case of an error, try { this.doSomething(); } catch (error) { console.error(error); } This problem occurs when "doSomething" returns a promise or runs asynchronous code. doSome ...

Methods for defining a variable in React with Typescript without encountering the "Index signature is missing in type" issue

I am facing an issue while trying to declare a variable 'reports' and assigning it to an array of arrays containing string and number types. The problem arises when I try to assign it, resulting in errors. ... // Retrieving data from an API let ...

Utilizing absolute imports in Typescript directory structure

Our team has a preferred structure for organizing React code, which looks like this: components/ button.tsx slider.tsx index.ts helpers/ math.ts auth.ts index.ts constants/ config.ts api.ts index.ts In this setup, each ...

What is the best way to implement a hover effect on multiple rows within an HTML table using Angular?

I am currently working on developing a table preview feature to display events. I previously sought assistance here regarding positioning elements within the table and successfully resolved that issue. Applying the same principles, I am now attempting to c ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

Can you switch out the double quotation marks for single quotation marks?

I've been struggling to replace every double quote in a string with a single quote. Here's what I have tried: const str = '1998: merger by absorption of Scac-Delmas-Vieljeux by Bolloré Technologies to become \"Bolloré.'; console ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

The Vue $refs Object is classified as 'unidentified' in nature

I'm encountering an issue while attempting to utilize $refs in my Vue 3 application. Each time I try, I receive the Typescript error stating that "Object is of type 'unknown'". I am uncertain about how to resolve this problem. Here's ...

Undefined TypeScript Interface

Here's my situation: public retrieveConnections() : IUser[] { let connections: IUser[]; connections[0].Id = "test"; connections[0].Email = "asdasd"; return connections; } I know this might be a dumb question, but why is connecti ...

The process of ordering awaits using an asynchronous method

async fetchAndStoreRecords(): Promise<Records[]> { this.subRecords = await this.afs.collection<Records>('records') .valueChanges() .subscribe((data: Records[]) => { console.log('log before data ...

Avoiding caching of GET requests in Angular 2 for Internet Explorer 11

My rest endpoint successfully returns a list when calling GET, and I can also use POST to add new items or DELETE to remove them. This functionality is working perfectly in Firefox and Chrome, with the additional note that POST and DELETE also work in IE ...

Ways to showcase information retrieved from an API onto an Angular Material card

The process involves calling two different APIs. The first API gathers user information such as name, ID, and the IDs of applications where the user is registered. The second API retrieves details from each application based on its ID. Despite successfully ...

operating efficiently even when producing an incorrect output type

Exploring Typescript for the first time on Codepen.io has left me puzzled. I'm unsure why, despite defining the function signature and return type with an interface, I am able to return a different type without encountering any errors. Is there somet ...