Angular 11 showing invalid date when trying to edit date in reactive forms

Viewed 401

I am developing an application in net 5 and angular 11, and dates are causing me some problems. Everything works fine when I try to create new date, but when I try to edit the existing one, my input box is showing - invalid date. Moreover, I can create new date despite that message, but would really like to avoid the aforementioned message, I would to begin with be fine even with a simple message stated in the placeholder. Here is my code, thank you in advance everyone for your willingness to help me, and please accept my appologies if my question is not precise enough, still learning how to ask a proper question:):

import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { PatientAppointmentsService } from 'src/app/patient-appointments/patient- 
appointments.service';
import { IAppointmentSingle, INewAppointmentToCreateOrEdit } from 
'src/app/shared/models/appointment';
import { AppointmentsService } from '../appointments.service';

@Component({
selector: 'app-appointment-edit',
templateUrl: './appointment-edit.component.html',
styleUrls: ['./appointment-edit.component.scss']
})
export class AppointmentEditComponent implements OnInit {
appointmentForms: FormArray = this.fb.array([]);
officeList = [];
id: number;
appointmentnew: INewAppointmentToCreateOrEdit;
appointment: IAppointmentSingle;
errors: string[] = [];


 constructor(private appointmentsService: AppointmentsService,
          private patientappointmentsService: PatientAppointmentsService,
          private activatedRoute: ActivatedRoute,
          private router: Router,
          private fb: FormBuilder) { }

ngOnInit(): void {
this.id = this.activatedRoute.snapshot.params['id'];
this.appointmentsService.getOffices()
.subscribe(res => this.officeList = res as []);

this.patientappointmentsService.getApointmentForEdit(this.id).subscribe(
(appointment: INewAppointmentToCreateOrEdit) => {
this.appointmentForms.push(this.fb.group({
          id: [this.id],
          office1Id: [appointment.office1Id, Validators.required],
          patient1Id: [appointment.patient1Id, Validators.required],
          startDateAndTimeOfAppointment: [appointment.startDateAndTimeOfAppointment, 
 Validators.required],
          endDateAndTimeOfAppointment: [appointment.endDateAndTimeOfAppointment, 
 Validators.required],
          remarks: [appointment.remarks],
          status: [appointment.status, Validators.required]
        }));
  });
  }

 recordSubmit(fg: FormGroup) {
  this.appointmentsService.editAppointment(fg.value).subscribe(
    (res: any) => {
     this.router.navigateByUrl('appointments');
    }, error => {
        console.log(error);
        this.errors = error.errors;
      });
    }
 

And my template:

    <form [formGroup]="fg" *ngFor="let fg of appointmentForms.controls" 
   (submit)="recordSubmit(fg)"> 
            <input formControlName="id" id="id" class="form-control" hidden> 
            <div class="form-group row">
                <div class="col-md-12">           
                   <input type="text"
                   formControlName= "endDateAndTimeOfAppointment"
                   placeholder="End"
                   class="form-control"
                   bsDatepicker
                   [bsConfig]="{
                    containerClass: 'theme-green',
                    dateInputFormat: 'DD.MM.YYYY  HH:mm'
                  }">
                 </div>       
             </div>   
    <div class="form-group row">
                <div class="col-md-12">    
                    <label style="font-size: small;"><strong>Special Remarks:</strong></label>       
                    <textarea type="text"
                    class="form-control"
                    formControlName="remarks"
                    rows="4 " readonly="readonly"></textarea>
                 </div>      
             </div>   
              <div class="form-group text-center">
                <label class="radio-inline">
                    <input type="radio" value='true' formControlName='status'> Accept
                </label>
                <label class="radio-inline">
                    <input type="radio" value='false' formControlName='status' class="ml-3"> 
 Reject
                </label>
            </div>
   <div class="row" *ngIf="errors?.length > 0">
                <ul class="text-danger">
                    <li *ngFor="let error of errors">
                        {{error}}
                    </li>
                </ul>
            </div>
        
            <div class="peki form-group text-center">
                <button [disabled]='!fg.valid' class="btn btn-success mr-2" 
    type="submit">Save</button>
            </div>
        </form>
        

So instead showing "End" like it is stated in placeholoder, I get invalid date.

1 Answers

Replace those lines (Component)


startDateAndTimeOfAppointment: [new Date(appointment.startDateAndTimeOfAppointment), Validators.required],
endDateAndTimeOfAppointment: [new Date(appointment.endDateAndTimeOfAppointment), Validators.required],

(Template)


[bsConfig]="{ containerClass: 'theme-green', dateInputFormat: 'MMMM Do YYYY, h:mm:ss a' }"

Related