htmlangularprimeng

Skip Dropdown button in Primeng Autocomplete when pressing Tab


I am using primeng to use multiple autocompletes with dropdown in my Angular reactive form. The autocompletes are of the following form:

<p-autoComplete
  inputId="myInput"
  class="p-fluid"
  [dropdown]="true"
  formControlName="myFormControl"
  (completeMethod)="filter($event.query)"
  [suggestions]="suggestions"
  [forceSelection]="true"
  [showClear]="true"
  (onClear)="myFormControl.reset()"
  appendTo="body">
</p-autoComplete>

This works as expected. However, when using the tab key to jump from one input to the next, it also focuses the "open dropdown" button. I would like to skip focussing this button and jump straight to the next input field.

I can't use [tabindex]="-1" on the p-autocomplete element because then it just skips the whole autocomplete input, but I only want to skip the dropdown button.

Is there any way to achieve this? Thanks.


Solution

  • There is no in-built property to do this, so you need to create a custom directive to do this. It would look something like below, where we find the button and update the tab index to -1 using renderer2 and elementRef

    import { Directive, ElementRef, Renderer2 } from '@angular/core';
    
    @Directive({
      selector: '[noButtonFocus]',
      standalone: true,
    })
    export class NoButtonFocusDirective {
      constructor(private element: ElementRef, private renderer: Renderer2) {}
    
      ngAfterViewInit() {
        const dropdownButton = this.element.nativeElement.querySelector(
          '.p-autocomplete-dropdown'
        );
        if (dropdownButton) {
          this.renderer.setAttribute(dropdownButton, 'tabindex', '-1');
        }
      }
    }
    

    Parent Component:

    <div class="card flex justify-content-center">
      <p-autoComplete
        noButtonFocus
        [(ngModel)]="selectedCountry"
        [dropdown]="true"
        [suggestions]="filteredCountries"
        (completeMethod)="filterCountry($event)"
        field="name"
      />
    </div>
    

    Stackblitz Demo