Search code examples
angularprimengautofocusprimeng-dropdowns

PrimeNG Multiselect autofocus



Using PrimgNG v7.1.3 in Angular v7 project.

Implemented Multiselect (https://www.primefaces.org/primeng-7.1.3/#/multiselect), in a simple component.
Need to set focus on it when the page loads.

Below solution works for Dropdown but not for Multiselect:

In HTML: <p-dropdown #someDropdown></p-dropdown>

In Component:

import { Dropdown } from 'primeng/dropdown';
@ViewChild('someDropdown') someDropdown: Dropdown;

this.someDropdown.applyFocus();

But for Multiselect, it throws error that such method is not valid.

Tried the first answer in this SO link mentioned for "control within ngIf", still no luck: primeng: Setting focus on control
Checked the PrimeNG documentation and User Guide too but no mention of focusing feature.

Later also tried below. None of it worked.

this.someMultiSelect.focus();
this.someMultiSelect.applyFocus();

this.someMultiSelect.el.focus();
this.someMultiSelect.el.applyFocus();

this.someMultiSelect.el.nativeElement.focus();
this.someMultiSelect.el.nativeElement.applyFocus();

this.someMultiSelect.containerViewChild.focus();
this.someMultiSelect.containerViewChild.applyFocus();

this.someMultiSelect.containerViewChild.nativeElement.focus();
this.someMultiSelect.containerViewChild.nativeElement.applyFocus();

Stackblitz: https://stackblitz.com/edit/primeng-multiselect-autofocus

Please suggest.

Any help is appreciated.


Solution

  • you can get element by ViewChild and do this trick to make it highlighted.

    something like this:

    Component

    import { MultiSelect } from 'primeng/multiselect';
    
    export class AppComponent implements AfterViewInit {
      name = 'Angular';
    
      @ViewChild('someDropdown') someDropdown: MultiSelect; // <--- you need to import this from PrimeNG Library
    
     ngAfterViewInit() {
       setTimeout(() => {
         this.someDropdown.containerViewChild.nativeElement.click();  
         this.someDropdown.hide();
       }, 300);
    
      }
    
    

    Here is the Stackblitz example:

    https://stackblitz.com/edit/ngprime-multiselect-efpy6z?embed=1&file=src/app/app.component.ts