Angular date fields do not get patched

I have a form in my Angular application with three fields: NAME, START DATE, and END DATE. When I attempt to edit the form, the START DATE and END DATE fields are not being patched correctly. It seems like they might not be converting to date objects properly. Below is the relevant code for my component:

@Component({
  selector: 'add-claims-project',
  templateUrl: 'add-claims-project.component.html'
})
export class AddClaimsProjectComponent {
  @Input() claimDetails: any;
  @Input() selectedDataValue: any;
  @Output() closeEvent = new EventEmitter<string>();

  public validationService: ValidationService;
  private validationMessages: { [key: string]: { [key: string]: string } };
  public selectedStartDate: Date;
  public selectedEndDate: Date;

  public claimProjectForm = new FormGroup({
    id: new FormControl(0),
    projectName: new FormControl('', [
      Validators.required,
      NotAllWhitespaceValidator(),
      Validators.maxLength(100),
      Validators.pattern(alphanumericWithSepcialCharactersRegex())
    ], [
      ClaimProjectExistsValidator(this.adminClaimService)
    ]),
    startDate: new FormControl('', [Validators.required]),
    endDate: new FormControl('', [Validators.required]),
    claimId: new FormControl('')
  });

  constructor(
    private loadingService: LoadingService,
    private adminClaimService: AdminClaimService,
    private toaster: ToastrService
  ) { }

  ngOnInit(): void {
    debugger
    if (this.claimDetails) {
      this.initialiseValidationService();
      this.claimProjectForm.get('claimId').setValue(this.claimDetails.id);
      this.patchData();
    }
  }

  private patchData(): void {
    if (this.selectedDataValue) {
      debugger
      this.claimProjectForm.patchValue({
        id: this.selectedDataValue.id,
        projectName: this.selectedDataValue.name,
        startDate: this.convertToDateString(this.selectedDataValue.startDate),
        endDate: this.convertToDateString(this.selectedDataValue.endDate)
      });
    }
    this.validationService.setInitalValue();
  }

  private convertToDateString(dateString: string): string {
    console.log('Converting Date String:', dateString);
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
      console.error('Invalid Date:', dateString);
      return '';
    }
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    console.log('Formatted Date:', formattedDate);
    return formattedDate;
  }

  private initialiseValidationService(): void {
    this.validationMessages = {
      projectName: {
        required: 'Project Name is required',
        allWhitespace: 'Project Name cannot be all white spaces',
        maxlength: "Project Name can be max 100 characters",
        pattern: "Project Name should be alphanumeric with special symbols like & - @ ? _ / * , ; : ! ' . only",
        alreadyExists: "Project Name already exists"
      },
      startDate: {
        required: 'Start Date is required',
      },
      endDate: {
        required: 'End Date is required',
      }
    };
    this.validationService = new ValidationService(this.validationMessages, this.claimProjectForm);
    this.validationService.setInitalValue();
  }

  public checkIsFormValid(): boolean {
    return this.claimProjectForm && this.claimProjectForm.valid;
  }

  public save(): void {
    debugger
    this.loadingService.start();
    const payload = this.assignValueToModel();
    const observable = !this.selectedDataValue ?
      this.adminClaimService.addClaimProject(payload) :
      this.adminClaimService.updateClaimProject(payload);

    observable.subscribe(
      (response: any) => {
        this.loadingService.stop();
        if (!this.selectedDataValue) {
          showSuccessMessage("Project Added Successfully", this.toaster);
        } else {
          showSuccessMessage("Project Updated Successfully", this.toaster);
        }
        this.close();
      },
      (error) => {
        this.loadingService.stop();
        if (!this.selectedDataValue) {
          showErrorMessage(error, "Error While Adding Project", this.toaster);
        } else {
          showErrorMessage(error, "Error While Updating Project", this.toaster);
        }
        this.close();
      }
    );
  }

  public close(): void {
    this.closeEvent.emit();
  }

  private assignValueToModel(): any {
    return {
      id: this.claimProjectForm.value.id,
      claimId: this.claimDetails.id,
      name: this.claimProjectForm.value.projectName,
      startDate: getMomentDateTimeToSave(this.claimProjectForm.value.startDate),
      endDate: getMomentDateTimeToSave(this.claimProjectForm.value.endDate)
    }
  }

  public onStartDateChange(): void {
    const startDate = this.claimProjectForm.get('startDate').value;
    if (startDate) {
      this.selectedStartDate = new Date(Date.parse(startDate));
      this.claimProjectForm.get('endDate').setValue(null);
    }
  }

  public onEndDateChange(): void {
    const endDate = this.claimProjectForm.get('endDate').value;
    if (endDate) {
      this.selectedEndDate = new Date(Date.parse(endDate));
    }
  }

  public getTitle(): string {
    return this.selectedDataValue ? "Update Project Details" : "Add Project Detail";
  }

Could you help me identify why the date fields are not being patched correctly and how I can fix this issue?”

New contributor

Dividutt Namboodiri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật