2

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. Got it working. What does split('.')?.[0]; do btw?
@ElaineByene It converts the date to 2024-07-05T09:42:00 by splitting on the . Then it gets converted into ['2024-07-05T09:42:00', '000Z'] here we access the zeroth element, which is our expected output!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.