Angular/PrimeNg: Focus on input each time I open a p-dialog

Viewed 4200

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?

2 Answers

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);
  }

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.

Related