Search code examples
javascripthtmlangulardatetimejava-time

Bind saved Date in Edit Form using Angular 17


I have a form where the date is entered and saved but the date is not binded when I go to edit the form.

JSON:

"checkOut": {
    "runDate": "2024-07-05T09:42:00.000Z",
}

The form is:

<input type="datetime-local" [(ngModel)]="checkOut.runDate">

Date is shown by binding like this:

{{source.room.checkOut?.runDate | date:"dd MMM, yyyy"}}

When I go to edit the form, I want the input field [(ngModel)]="checkOut.runDate" to be pre-filled if the date is already entered. How can I achieve this?


Solution

  • Datetime local excepts the input to be like 2024-07-05T09:42:00, So we can transform it to suit the requirement.

    ngOnInit() {
        this.checkOut.runDate = this.checkOut?.runDate?.split('.')?.[0];
    }
    

    Full Code:

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [FormsModule, CommonModule],
      template: `
       <input type="datetime-local" [(ngModel)]="checkOut.runDate">
       <br/>
       {{checkOut.runDate | date:"long"}}
      `,
    })
    export class App {
      checkOut: any = {
        runDate: '2024-07-05T09:42:00.000Z',
      };
    
      ngOnInit() {
        this.checkOut.runDate = this.checkOut?.runDate?.split('.')?.[0];
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo