Search code examples
angularfocusprimeng

How to focus on PrimeNG p-button


I have a form in Angular. On pressing Enter key I would like to focus on the next control. On keyup.enter event for each input I use the ref of the next input and call focus(). But this isn't working for p-button.

<div class="p-field p-col-12 p-md-6">
  <label>Address Line 1</label>
  <input #regAddressLine1 type="text" pInputText [readonly]="!editMode" formControlName="regAddressLine1" (keyup.enter)="regAddressLine2.focus()">
  <small class="p-invalid" *ngIf="f.regAddressLine1.invalid && f.regAddressLine1.touched">Required</small>
</div>
<div class="p-field p-col-12 p-md-6">
  <label>Address Line 2</label>
  <input #regAddressLine2 type="text" pInputText [readonly]="!editMode" formControlName="regAddressLine2" (keyup.enter)="save.focus()">
  <small class="p-invalid" *ngIf="f.regAddressLine2.invalid && f.regAddressLine2.touched">Required</small>
</div>
<div class="p-col-12 p-md-3">
  <p-button #save label="Save" styleClass="p-button-primary">
  </p-button>
</div>

Solution

  • Looks like p-button component doesn't have such method.

    I would consider using attribute version of primeng button:

    <button #save pButton label="Save" styleClass="p-button-primary" type="button"></button>
                  ^^^^^^^^
    

    This way #save template variable is referring to native HTMLButtonElement which has focus() method.

    Forked Stackblitz