From 6e95435b4c39a00f3ce7b6f2540e84c7b4a76d13 Mon Sep 17 00:00:00 2001 From: Fynn Feldpausch Date: Wed, 24 Apr 2024 10:28:54 +0200 Subject: [PATCH] fix(angular): correctly handle range values in angular value accessor of datepicker --- .../src/lib/directives/date-value-accessor.ts | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/angular/projects/catalyst/src/lib/directives/date-value-accessor.ts b/angular/projects/catalyst/src/lib/directives/date-value-accessor.ts index 9f042a228..14fd5148e 100644 --- a/angular/projects/catalyst/src/lib/directives/date-value-accessor.ts +++ b/angular/projects/catalyst/src/lib/directives/date-value-accessor.ts @@ -25,16 +25,33 @@ export class DateValueAccessor extends ValueAccessor { return this.el.nativeElement; } writeValue(value: any) { - if (value && value instanceof Date) { + if (!this.el.nativeElement.range) { + return super.writeValue(this.toISO(value)); + } else if (value instanceof Array) { + const data = [this.toISO(value[0]), this.toISO(value[1])]; + return super.writeValue(JSON.stringify(data)); + } + return super.writeValue(undefined); + } + handleChangeEvent(value: any) { + if (!this.el.nativeElement.range) { + return super.handleChangeEvent(this.toDate(value)); + } else if (typeof value === 'string') { + return super.handleChangeEvent(JSON.parse(value).map(this.toDate)); + } + super.handleChangeEvent(null); + } + private toISO(value: any) { + if (value instanceof Date) { const year = value.getFullYear(); const month = (value.getMonth() + 1).toString().padStart(2, '0'); const day = value.getDate().toString().padStart(2, '0'); - return super.writeValue(`${year}-${month}-${day}`); + return `${year}-${month}-${day}`; } - return super.writeValue(undefined); + return undefined; } - handleChangeEvent(value: any) { + private toDate(value: any) { const [match, year, month, day] = value?.match(/^(\d{4})-(\d{2})-(\d{2})/) ?? []; - return super.handleChangeEvent(match ? new Date(Number(year), Number(month) - 1, Number(day)) : null); + return match ? new Date(Number(year), Number(month) - 1, Number(day)) : null; } }