简体   繁体   中英

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

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.

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

ts:

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

html:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM