htmlangularprimeng

Can you implement a PrimeNG SelectItem as a menu item that retains focus?


I have a front-end Angular app that uses a PrimeNG SelectItem interface to implement the application's main menu.

/**
 * Represents an option item.
 * @group Interface
 */
export interface SelectItem<T = any> {
    label?: string;
    value: T;
    styleClass?: string;
    icon?: string;
    title?: string;
    disabled?: boolean;
}

and I put it in a NavigationComponent class like this:

export class NavigationComponent implements OnInit {

    pages: SelectItem[] = [
    {
       label: 'Home',
       value: 'home'
    },
    {
       label: 'Page One',
       value: 'PageOne'
    }

For the most part this works fine - except that I would like for a menu item to retain its focus once it is selected.

Would like the menu item to remain selected

However it loses focus as soon as the page loads

Is there an easy way to have the menu items retain their focus?

Thanks much


Solution

  • Try using RouterLink with routerLinkActive to add an active class.
    ex:

    @for (page of pages; track $index) {
      <a [routerLink]="page.value" routerLinkActive="active">{{ page.label }}</a>
    }
    

    which is the active should be a class to change the item style.
    You can set it, for example, routerLinkActive="text-primary bg-white"