Within my Angular + Angular Material application, I am facing an issue with a date range picker. My goal is to send the selected start and end dates in a formatted manner through an API call. However, when the date values are sent over the API as part of the payload, they include the whole date with hours, minutes, seconds, time zone, etc. I only want to send a formatted date (e.g., 2023-09-11).
Despite formatting the date on my end, upon clicking "apply" on the form, the date sent in the payload still includes the complete information. Why is the datepicker overriding my formatted date, or could there be a mistake in my code?
In the component.html file:
<mat-form-field appearance="fill">
<mat-label>Enter date:</mat-label>
<mat-date-range-input ngModel [formGroup]="range" [rangePicker]="picker">
<input matStartDate formControlName="start" placeholder="Start date" >
<input matEndDate formControlName="end" placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker>
<mat-date-range-picker-actions>
<button mat-button matDateRangePickerCancel>Cancel</button>
<button mat-raised-button color="primary" matDateRangePickerApply (click)="getSingleCustomerRangeChartData($event)">Apply</button>
</mat-date-range-picker-actions>
</mat-date-range-picker>
</mat-form-field>
In the component.ts file:
setDate: any = new Date().toISOString().substring(0, 10);
range: FormGroup;
constructor() {
this.range = new FormGroup({
start: new FormControl(this.setDate),
end: new FormControl(this.setDate),
})
}
getSingleCustomerRangeChartData(event: any) {
const id = Number(this.route.snapshot.paramMap.get('id'));
this.customerService.getSingleCustomerRangeChartData(id, this.range.value).subscribe(
data => {
this.prodajaChart = data;
console.log('Selected dates: ', this.range.value);
},
error => {
console.log('Error', error);
});
}
In the service.ts file:
getSingleCustomerRangeChartData(id:number, range: any) {
let queryParams = new HttpParams();
Object.keys(range).forEach((key) => {
if (range[key] !== null) {
queryParams = queryParams.append(key, range[key]);
}
});
return this.httpClient.get<typeof prodajaChart>(`${environment.apiUrl}stat/sale/${id}`,{params:queryParams})
}