[英]Can I add accelerators to enter a date in a Angular Material Datepicker field?
我正在使用 Angular 開發 web 應用程序。 有沒有辦法向日期輸入添加快捷方式/加速器? 例如,用戶應該能夠鍵入“+1”並將輸入解析為明天的日期。 至少我希望能夠將輸入“6-18”設置為 6-18-2020 而不是 6-18-2001。
我正在使用 Angular 9 和材料 8。
以下是我如何解決這個問題,以防其他人有同樣的問題。 這允許通過 +1(明天)、-1(昨天)等輸入日期。
我創建了一個指令...
export class DateEntryShortcutsDirective {
// form control bound to datepicker input
@Input() control: FormControl;
constructor() {}
// listen for change events on the datepicker input
@HostListener('change', ['$event']) onChange(event: any) {
this.setDate(event.target.value);
}
setDate(data) {
if (typeof data === 'string' && data.length) {
// if values begins with '+'
if (data.substring(0, 1) === '+') {
// get current date and advance by however many days requested
const dayDiff = +data.substring(1);
const date = new Date(
new Date().getTime() + dayDiff * 24 * 60 * 60 * 1000
);
// set the control value to date
if (this.control) {
this.control.setValue(date);
}
} else if (data.substring(0, 1) === '-') {
// if value begins with '-'
// get current day and subtract days
const dayDiff = +data.substring(1);
const date = new Date(
new Date().getTime() - dayDiff * 24 * 60 * 60 * 1000
);
// set control to date
if (this.control) {
this.control.setValue(date);
}
}
}
}
}
然后像這樣使用該指令......
<mat-form-field class="mat-form-field date items">
<mat-label>Deliver NLT</mat-label>
<input
tabindex="{{ 80 + index * 1500 }}"
matInput
autocomplete="off"
[matDatepicker]="receiverNLTDate"
placeholder="Date NLT"
formControlName="receiverNoLaterThanDate"
(dateChange)="onReceiverNoLaterThanChanges()"
[min]="
this.data.reference.freightUnits[this.index]
.receiverRequestedDeliveryDate
"
appDateEntryShortcuts
[control]="receiverNoLaterThanDate"
/>
<mat-datepicker-toggle
matSuffix
[for]="receiverNLTDate"
></mat-datepicker-toggle>
<mat-datepicker #receiverNLTDate></mat-datepicker>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.