Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading