Focus Filterfield of ng-multiselect-dropdown automatically when clicked

1.1k Views Asked by At

I'm using the ng-multiselect-dropdown package (https://www.npmjs.com/package/ng-multiselect-dropdown) in my angular project. Everything works fine, but I want to focus the filter input field automatically when I open the multiselect dropdown.

Here is my html code:

<div class="input-group" style="display: flex">
                <span class="input-group-text"><i class="fas fa-building"></i></span>
                <ng-multiselect-dropdown style="flex: 1"
                                         [placeholder]="'Unternehmen'"
                                         [data]="this.companies"
                                         [formControl]="filterCompany"
                                         [settings]="dropdownSettingsCompanies"
                                         (onFilterChange)="updateCompanyList($event)"
                                         (onSelect)="onItemSelect($event)">
                </ng-multiselect-dropdown>
</div>

And here are my settings for the multiselect:

dropdownSettingsCompanies: any = {
        singleSelection: false,
        idField: 'id',
        textField: 'name',
        showSelectedItemsAtTop: true,
        clearSearchFilter: true,
        allowSearchFilter: this.ShowFilter,
        enableCheckAll: false,
        allowRemoteDataSearch: true,
        searchPlaceholderText: 'Bitte geben Sie einen Suchbegriff ein',
    };

1

There are 1 best solutions below

0
On BEST ANSWER

The project does not have this feature internally, you need to write your own way. I am using a directive and getting the input element using querySelector and focusing the input!

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appFocusOnClick]',
})
export class FocusOnClickDirective {
  constructor(private elementRef: ElementRef) {}

  @HostListener('click', ['$event.target'])
  onClick(btn) {
    console.log('button', btn, 'number of clicks:');
    const input = this.elementRef.nativeElement.querySelector(
      '.filter-textbox > input'
    );
    if (input) {
      input.focus();
    }
  }
}

stackblitz