0
votes

Is it possible to close the Mat Datepicker Calendar window when pressing the enter key? Right now if I click my form input field the calendar opens. I want to be able to press the enter key but close the calendar window and not have it stay open.


<form #form="ngForm" (keyup.enter)="sumbitByEnter($event)">
    <mat-form-field floatLabel="never">
      <input name="id" matInput placeholder="Search for student by ID number" 
      [(ngModel)]="model.id" minlength="9" maxlength="9" #uname="ngModel">
    </mat-form-field>

<mat-form-field>
   <input name="startDate" matInput [max]="model.endDate" [matDatepicker]="picker" 
   (click)="picker.open()" (focus)="picker?.open()" placeholder="Start Date" 
   [(ngModel)]="model.startDate">
       <mat-datepicker-toggle matSuffix></mat-datepicker-toggle>
       <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

</form>

1
can you provide minimal reproduce issue in stackblitz.com?.Arunkumar Ramasamy

1 Answers

1
votes

You can get access to your date picker via @ViewChild and to listed for global enter event and then once user press enter you can catch this event end call "close()" which will close the panel. So it will be like this in your TS file:

// getting reference to date picker
@ViewChild(MatDatepicker) private rangePicker: MatDatepicker<Date>;

globalEnter = fromEvent<KeyboardEvent>(document, 'keyup')
      .pipe(
        filter((event) => event.keyCode === ENTER),
        tap(console.log)
      )
      .subscribe(() => this.rangePicker.close())

Of course import all imports (ENTER you can import from '@angular/cdk/keycodes') and also handle unsubscribtion properly etc.