Custom Date Picker Based On MatDatePicker - Open Picker and Focus Input

时间:2018-12-03 13:08:18

标签: angular angular-material2 angular7

Stackblitz Example

Hi community I created a custom date picker component that is based on the Angular Material DatePicker. It has the following additional features:

  • input mask for German date format
  • Opening calendar when clicking input field

When clicking input field (background color: brown), the calendar opens and the input field is focused. So the user can either choose a date from the calendar or type it manually into the input field.

When clicking the mat-form-field (background color: white), the input field gets focused by default. I grap the click event to additionally open the datepicker:

<mat-form-field (click)="datePicker.open();">

The calendar opens but the input field does not get focused. Even when I add the focus-method to the click-eventhandler, the input field does not get focused:

 <mat-form-field (click)="datePicker.open(); input.focus()">

It seems like I had to choose if I'd like to have the calendar open or the input field focused when clicking the mat-form-field, but I want both :-)

Another unsuccessful approach was to grap the onContainerClick event of the mat-form-field.

I also tried to call the input.click() method in the mat-form-field.click() method but also without success.

Any ideas how I can achieve the same behaviour on clicking the mat-form-field that I get when clicking the input field?

Thank you very much.

1 个答案:

答案 0 :(得分:0)

我成功地将this.dateInput.nativeElement.focus()方法调用放入了setTimeout函数中:

模板:

<mat-form-field (click)="datePicker.open(); focusInputField();">

后面的代码:

  focusInputField() {
    setTimeout(() => this.dateInput.nativeElement.focus());
  }

我更新了stackblitz示例。