'PrimeNG <p-menu> how to keep click menu item selected (Angular 7)

I am using primeNg component in angular 7 project.

<p-menu [model]="items" ></p-menu>

while dealing with this component we don't have access to its internal structure to show click menu item as selected. to push active class when a certain menu will be selected and change its color.

Does anybody have any idea about this?



Solution 1:[1]

For PrimeNG 10 I had to do tweak the code by Surendranath the following way:

Template:

<p-menu [model]="items" (click) = "activeMenu($event)"></p-menu>

Component:

  activeMenu(event) {
    //console.log(event.target.classList);
    let node;
    if (event.target.classList.contains("p-submenu-header") == true) {
      node = "submenu";
    } else if (event.target.tagName === "SPAN") {
      node = event.target.parentNode.parentNode;
    } else {
      node = event.target.parentNode;
    }
    //console.log(node);
    if (node != "submenu") {
      let menuitem = document.getElementsByClassName("p-menuitem");
      for (let i = 0; i < menuitem.length; i++) {
        menuitem[i].classList.remove("active");
      }
      node.classList.add("active");
    }
  }

Global Style (not Component Style)

.p-menuitem.active {
  background-color: orange;
}

Solution 2:[2]

Thank you for this SURENDRANATH SONAWANE - first solution that worked for me after trying many others.

In case this helps anyone, I couldn't get my CSS class recognized, had to add the following notation in .css (note the :host >>> prefix)

:host >>> .active {
    background-color: #b8ebf5;
}

...also, for a default menu item, pre-select it in MenuIItem[] definition by setting styleClass, e.g.:

        this.items = [
           {label: 'Search' , url : '/#/query' , styleClass : 'active'}, // Default item
           {label: 'Stats'  , url : '/#/stats' },
           {label: 'User'   , url : '/#/user'  }
        ]

Solution 3:[3]

html:

<p-menu 
    [model]="[
     { label: 'a', command: onClick() ,styleClass : getClassByLabel('a') },
     { label: 'b', command: onClick() ,styleClass : getClassByLabel('b') }
    ]"
><p-menu>

ts:

  currentModel: any;

  onClick() {
    return (event) => this.currentModel = event.item;
  }

  getClassByLabel(label: string): string {
    if (this.currentModel && this.currentModel.label == label) {
      return 'active';
    }
  }

style.css:

p-menu > div > ul > li.active > a > span {
  color: color:blue !important;
}

Solution 4:[4]

I am using Angular 13.0.2 and Primeng 13.0.0

I add the following code to myComponent.component.css not global styles.scss

::ng-deep .p-menuitem-link-active{
  background-color: #FED201!important;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Satish
Solution 2 Grits
Solution 3
Solution 4 CodeChanger