Search code examples
javascriptangulartypescriptangular-ngselect

Unable to focus on a custom submit button in Angular @ng-select


I am using ng-select library. In multiselect, after checking the checkboxes, I need to have a custom submit button.

Everything is is working fine, but since key-board navigation is very important, I want to focus on submit button on TAB press.

Here is my code:

Template:

  <ng-container >
    <ng-select #entitySelector (remove)="onEntityChange($event)" [items]="people$ | async" [multiple]="true" bindLabel="name" [closeOnSelect]="false" bindValue="name" [(ngModel)]="tempSelectList"
      [virtualScroll]="true" placeholder="Search People"  (keydown.Tab)="onTabPress($event)" >
      <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
        <input id="item-{{index}}" type="checkbox" [ngModel]="item$.selected" /> {{item.name}}
      </ng-template>
      <ng-template ng-footer-tmp>
        <input type="submit" id="selectEntityBtn" value="Select" #selectEntityBtn class="btn btn-default select-button" (click)="saveData()"/>
      </ng-template>
    </ng-select>
  </ng-container>

TS:

  onTabPress() {
    var that = this;
    setTimeout(() => {
      that.entitySelector.open();
      // that.selectEntityBtn.nativeElement.focus();
      document.getElementById("selectEntityBtn").focus();
    }, 1);
  }

Stackbiltz link

Please help me out :)


Solution

  • You need event.preventDefault() to disable default tab behavior on browser, so try this:

    onTabPress(event) {
        var that = this;
        setTimeout(() => {
          that.entitySelector.open();
          // that.selectEntityBtn.nativeElement.focus();
          document.getElementById("selectEntityBtn").focus();
        }, 1);
        event.preventDefault();
    }
    

    Stackblitz working demo