Home > Mobile >  How to get the selected item from Primeng Panelmenu
How to get the selected item from Primeng Panelmenu

Time:10-24

I'm using Panelmenu from Primeng. When someone clicked to an item in this Panelmenu, I want to get that item.

<p-sidebar [(visible)]="display">
    <p-panelMenu [model]="sidebarItems" [style]="{'width':'280px'}"></p-panelMenu>
</p-sidebar>

For example, if someone choose the Apartment option from below, I want to get it. How can i achieve this?

this.sidebarItems = [
      {
        label:'Home',
        icon:'pi pi-fw pi-home',
        routerLink: '/home',
        items: [
          {label:'Apartment',
          icon:'pi pi-fw pi-home',
          routerLink: '/apartment',}
        ]
      },
      {
        label:'Contact',
        icon:'pi pi-fw pi-phone',
        routerLink: ['/contact'],
      },
  ];

CodePudding user response:

You can add commands to every menu item that would save the active item:

activeItem: MenuItem;
...
{
  label: 'Contact',
  icon: 'pi pi-fw pi-phone',
  routerLink: ['/contact'],
  command: e => this.activeItem = e.item,
}

You can also apply this to every item and sub item of the menu:

 private fixupItems(items: MenuItem[]): void {
   items?.forEach((item) => {
     item.command = (e) => (this.activeItem = e.item);
     this.fixupItems(item.items);
   });
 }

StackBlitz

  • Related