Format of data.date is "2023-04-01T00:00:00.000Z" . I want t" /> Format of data.date is "2023-04-01T00:00:00.000Z" . I want t" /> Format of data.date is "2023-04-01T00:00:00.000Z" . I want t"/>

Display date using ngModel in angular

1.9k Views Asked by At

I have an input field and code is as follows:

<input type="Date" [(ngModel)]="data.date">

Format of data.date is "2023-04-01T00:00:00.000Z" . I want to show date input field in dd-mm-yyyy format.

But date is not getting displayed in input. How can I display date in input using ngModel?

1

There are 1 best solutions below

0
Wandrille On

To display the date in the desired format in the input field using ngModel, you need to convert the date string to a Date object and then format it using Angular's built-in DatePipe. Here's how you can do it:

  1. Import the DatePipe from '@angular/common' in your component and use it for the formatting:
import { DatePipe } from '@angular/common';

...

constructor(private datePipe: DatePipe) { }

get formattedDate() {
  return this.datePipe.transform(this.data.date, 'dd-MM-yyyy');
}

  1. Update the ngModel binding in your template to use the formatted date:
<input type="date" [ngModel]="formattedDate" (ngModelChange)="data.date=$event">

Note that the input type should be "date" and not "Date" for this to work properly.