javascriptangulardropdownprimeng

How to access PrimeNG Dropdown 's OverlayOptions OnBeforeShow Callback?


Is it possible to listen for a dropdowns overlay event that it is about to open?

the Dropdown's OverlayOptions offer OnBeforeShow Callback, but I am not able to use/access it.

Something like

<p-dropdown
  #dropdown
  (onBeforeShow)="doSomething()"
</p-dropdown>

Or

this.dropdown.overlayOptions.onBeforeShow((e) => {
  doSomething(e);
}

would be cool.


Solution

  • We need to access the view child of the overlay.

    For this, we can use the property overlayViewChild

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ImportsModule } from './imports';
    import { Dropdown } from 'primeng/dropdown';
    import { Subscription } from 'rxjs';
    interface City {
      name: string;
      code: string;
    }
    
    @Component({
      selector: 'dropdown-basic-demo',
      templateUrl: './dropdown-basic-demo.html',
      standalone: true,
      imports: [ImportsModule],
    })
    export class DropdownBasicDemo implements OnInit {
      private sub: Subscription = new Subscription();
      @ViewChild(Dropdown) pdropdown!: Dropdown;
      cities: City[] | undefined;
    
      selectedCity: City | undefined;
    
      ngOnInit() {
        this.cities = [
          { name: 'New York', code: 'NY' },
          { name: 'Rome', code: 'RM' },
          { name: 'London', code: 'LDN' },
          { name: 'Istanbul', code: 'IST' },
          { name: 'Paris', code: 'PRS' },
        ];
      }
    
      ngAfterViewInit() {
        this.sub.add(
          this.pdropdown.overlayViewChild.onBeforeShow.subscribe((event: any) => {
            console.log('from listener', event);
          })
        );
      }
    
      doSomething() {
        console.log('something');
      }
    
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
    

    Stackblitz Demo