Home > Blockchain >  How can I set focus to datepicker or input field after the datepicker.close() call in angular
How can I set focus to datepicker or input field after the datepicker.close() call in angular

Time:09-07

I have an angular page. In a mat-form-field, I've created a datepicker the gets the year and month only so I made a onMonthSelect function.

picker.component.html

    <input
       matInput
       [matdatePicker]="picker"
     >
    <mat-datepicker #picker (monthSelected)="onMonthSelect($envent, picker)">
    </mat-datepicker>*

picker.component.ts

    onMonthSelect(date: Moment, datepicker){<br>
       datepicker.close();*

            Here I want to put the focus back to matInput

    }

After calling the datepicker.close(), the focus or cursor goes somewhere on top of the page instead on the next input field. When I press tab after the datepicker closes, it focus at top not the next <div> or component. I want to force the focus to go back to matInput or matPicker. I tried tabindex, but not working.

CodePudding user response:

It's got closed as Output for you.

You can get close event by return to any functions like this

<mat-datepicker #picker (closed)="closeEvent($event)"></mat-datepicker>

or simply set focus to other element instead

<mat-datepicker #picker2 (closed)="fieldB.focus()"></mat-datepicker>

Example: stackblitz

Reference: https://material.angular.io/components/datepicker/api

CodePudding user response:

ts:

datePickerFocus(){
  setTimeout(() => { 
  document.getElementById('picker2')?.focus(); ]
  }, 100);
}

html:

<mat-datepicker #picker2 (closed)="datePickerFocus()"></mat-datepicker>
  • Related