1

I open a p-dialog with a p-inputNumber inside, but I don't manage to set focus on it.

I tried to put autofocus, as you see, but it doesn't work. The focus remains on the button I pressed to open the dialog. How can I do? Thanks.

<p-dialog header="Title" [(visible)]="displayModal" [modal]="true" [style]="{width: '40vw'}"
  [baseZIndex]="10000" [draggable]="false" [resizable]="false" [closable]="false">
  <p class="p-m-0">
    <p-inputNumber size=3 [(ngModel)]="field" maxlength="3" autofocus></p-inputNumber>
  </p>
  <ng-template pTemplate="footer">
    <button >Ok</button>
  </ng-template>
</p-dialog>
Antikhippe
  • 6,316
  • 2
  • 28
  • 43
doinel
  • 87
  • 1
  • 9

1 Answers1

2

First, add a reference to your input in order to manipulate it from typescript via a ViewChild:

<p-inputNumber size=3 [(ngModel)]="field" maxlength="3" #input></p-inputNumber>

and

@ViewChild("input") elm;

Then, set the focus to this input once the dialog shows up by using onShow method:

(onShow)="setFocus()"

and

setFocus() {
    this.elm.input.nativeElement.focus();
}

See demo

Antikhippe
  • 6,316
  • 2
  • 28
  • 43