【问题标题】:Can I add accelerators to enter a date in a Angular Material Datepicker field?我可以添加加速器以在 Angular Material Datepicker 字段中输入日期吗?
【发布时间】:2020-06-18 17:02:06
【问题描述】:

我正在使用 Angular 开发一个 Web 应用程序。有没有办法向日期输入添加快捷方式/加速器?例如,用户应该能够键入“+1”并将输入解析为明天的日期。至少我希望能够将输入“6-18”设置为 6-18-2020 而不是 6-18-2001。

我正在使用 Angular 9 和 Material 8。

【问题讨论】:

  • 您好!如果您能提供代码 sn-p 甚至更好的代码,一个 jsfiddle 不工作代码示例,这将对您有所帮助。这有助于人们尝试解决方案,最终他们将能够为您提供您想要实现的目标的工作示例。另外请务必分享您使用的是哪个版本的 Angular 和 Angular Material,因为它可以决定答案。

标签: angular angular-material angular-material-datetimepicker


【解决方案1】:

如果其他人有同样的问题,我就是这样解决这个问题的。这允许通过 +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>

编辑

在获得更多了解后,我现在扩展 Native Date Adapter 并用我自己的覆盖它的解析函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2020-09-29
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多