8

I'd like to auto focus a certain input field which is in a p-dialog component, which is opened/closed by a flag that is bind to the dialog's visible attribute.

When I add an "autofocus" attribute to the input tag - it is focused only in the first time the dialog is opened.

When I use the "onShow" event - it is emitted BEFORE the dialog is open.

When I add an "autofocus" directive and try to set the focus in AfterViewInit - it is called only once.

Anyone knows how I can set the focus or get a "onAfterShow" event for the dialog?

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
Tal Sheffer
  • 155
  • 1
  • 10
  • expecting some code to solve your issue - event when dialog triggered and the input you want focus when dialog is shown – Rahul Nov 08 '18 at 10:09

2 Answers2

0

I use a setTimeout to set the focus of element after specific time base on the form appearance as example 500 millisecond

template

<p-dialog [header]="dialogTitle" [(visible)]="isDialogVisible" [responsive]="true" 
   [appendTo]="'body'" (onShow)="setFocus(txtElement)">
     <input #txtElement >
</p-dialog>

component

setFocus(elm: HTMLInputElement) {
    setTimeout(() => {
      elm.focus()
    }, 500);
  }
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
  • I did something similar, but: (1) it is not a "clean" solution (2) sometimes my app is heavy and the timeout may not be enough. Isn't there a more elegant solution to this problem? I assume it is a main-stream use case... – Tal Sheffer Nov 08 '18 at 10:21
  • the do have a proprty for button focusOnShow so I guess we need to ask for another proprty like focusOnShowElement so the best case is to open an issue on github repo – Muhammed Albarmavi Nov 08 '18 at 10:34
  • check this https://stackoverflow.com/questions/15247849/how-to-set-focus-to-first-text-input-in-a-bootstrap-modal-after-shown onShow dons't work like showing I think – Muhammed Albarmavi Nov 08 '18 at 10:37
0

You didn't share your code, but my best guess would be that you're relying on [(visible)]="dialogShown" to show/hide your p-dialog. If you would also add *ngIf="dialogShown" then it would force regeneration of the dialog each time, and would also cause autofocus to be treated accordingly.

noamyg
  • 2,747
  • 1
  • 23
  • 44