我试图在我的角度应用程序中使用jQuery Datepicker。 从服务器我得到一个日期对象,格式为yy-mm-dd。当我将此格式设置为" dateFormat"选项我的日期显示正确。 但我喜欢只为UI获取以下格式:dd.mm.yy。 当我在选项中设置此格式时,日期1959-12-31结果为05.03.2022。 如果我单击“保存”按钮,这也是我从datepicker获得的格式。 所以唯一的工作格式是yy-mm-dd,如果有人可以帮助我,那就太好了。我尝试了很多其他选项,并在这里阅读了许多其他类似的问题,但我无法获得任何解决方案。 我还尝试了一个隐藏的输入字段来存储备用值。
这是我的Angular组件使用jQuery选择器:
import {forwardRef, Input, Output, EventEmitter, ViewChild, ElementRef, AfterViewInit, Component} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";
const DATE_PICKER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DatePicker),
multi: true
};
declare var jQuery: any;
@Component({
selector: 'jQueryDate',
template: `<input #datePickerInput type="text">
<input type="hidden" id="datePickerAlternate" #datePickerAlternate>`,
providers: [DATE_PICKER_VALUE_ACCESSOR]
})
export class DatePicker implements AfterViewInit {
private onTouched = () => {
};
private onChange: (value: string) => void = () => {
};
@Input() options: any = {
closeText: "Schließen",
prevText: "<Zurück",
nextText: "Vor>",
currentText: "Heute",
dateFormat: 'dd.mm.yy',
isRTL: false,
showMonthAfterYear: false,
altField: "#datePickerAlternate",
altFormat: "yy-mm-dd",
dayNames: ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"],
monthNames: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
dayNamesMin: ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"],
weekHeader: "KW",
firstDay: 0
};
@Input() value: Date;
writeValue(date: Date) {
console.log("datepicker value " + date);
jQuery(this.input.nativeElement).datepicker('setDate', date);
this.alternate.nativeElement.value = date;
console.log("value of alternate: " + this.alternate.nativeElement.value);
}
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouched = fn;
}
@Output() dateChange = new EventEmitter();
@ViewChild('datePickerInput') input: ElementRef;
@ViewChild('datePickerAlternate') alternate: ElementRef;
ngAfterViewInit() {
jQuery(this.input.nativeElement).datepicker(Object.assign({}, this.options, {
onSelect: (value) => {
this.value = value;
this.onChange(value);
this.onTouched();
this.alternate.nativeElement.value = value;
this.dateChange.next(value);
}
}))
.datepicker('setDate', this.value);
}
}
以下是组件的使用:
<jQueryDate class="" name="txtBirthdate" #txtBirthdate="ngModel" type="date" id="txtBirthdate"
[(ngModel)]="this.person.txtBirthdate" ngDefaultControl></jQueryDate>