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?”
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