[英]Can I add accelerators to enter a date in a Angular Material Datepicker field?
I am working on a web application using Angular.我正在使用 Angular 开发 web 应用程序。 Is there a way to add shortcuts/accelerators to the date input?有没有办法向日期输入添加快捷方式/加速器? For example, a user should be able to type "+1" and have the input resolve to tomorrow's date.例如,用户应该能够键入“+1”并将输入解析为明天的日期。 At the very least I would like to be able to set an input of "6-18" to 6-18-2020 instead of 6-18-2001.至少我希望能够将输入“6-18”设置为 6-18-2020 而不是 6-18-2001。
I am using Angular 9 and Material 8.我正在使用 Angular 9 和材料 8。
Here is how I solved this in case anyone else has the same issue.以下是我如何解决这个问题,以防其他人有同样的问题。 This enables dates to be entered via +1 (tomorrow), -1 (yesterday), etc.这允许通过 +1(明天)、-1(昨天)等输入日期。
I created a directive...我创建了一个指令...
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);
}
}
}
}
}
The directive is then used like so...然后像这样使用该指令......
<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.