codrut
codrut

Reputation: 89

How can I use a custom icon for a MenuItem in Angular and PrimeNG?

I am using Angular 18 and the RC version of PrimeNG 18 ("primeng": "^18.0.0-rc.1") I am trying to use a custom icon for the MenuBar component elements, since by default using icon: 'pi pi-home' in the MenuItem definition uses a PrimeNG icon. I have found this question asked and tried to implement this approach.

The issue is that it doesn't seem to work. This is my code:

app.ts:

menuItems: MenuItem[] | undefined = [
    {
      label: 'Tickets',
      icon: 'tickets-icon',
    }]

app.html:

<p-menubar [model]="menuItems">

app.css:

:host ::ng-deep {
  .tickets-icon {
    width: 1rem;
    height: 1rem;
    background-image: url("/assets/menuIcons/tickets.svg");
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
}

I made sure that the assets folder is correctly added in angular.json:

"assets": [
              "src/favicon.ico",
              "src/assets"
            ],

And that the path to the file is correct. I have also tested the icon to make sure the svg is valid. What am I missing?

Upvotes: 1

Views: 131

Answers (1)

Naren Murali
Naren Murali

Reputation: 57986

You are using css file, instead of scss file, hence the nested styling is not recognized, rename the file to app.component.scss and it should work.

Full Code:

TS:

import { Component, OnInit } from '@angular/core';
import { ImportsModule } from './imports';
import { MenuItem } from 'primeng/api';

@Component({
  selector: 'menu-group-demo',
  templateUrl: './menu-group-demo.html',
  standalone: true,
  styles: [
    `
    :host ::ng-deep {
        .tickets-icon {
            width: 1rem;
            height: 1rem;
            background-image: url("/assets/menuIcons/home.svg");
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
        }
    }
  `,
  ],
  imports: [ImportsModule],
})
export class MenuGroupDemo implements OnInit {
  items: MenuItem[] | undefined;

  ngOnInit() {
    this.items = [
      {
        label: 'Tickets',
        icon: 'tickets-icon',
      },
    ];
  }
}

HTML:

<div class="card flex justify-content-center">
    <p-menu [model]="items" />
</div>

Stackblitz Demo

Upvotes: 1

Related Questions