Jigna Rathod
Jigna Rathod

Reputation: 43

How to add custom svg icon and regular angular material icons to same mat-icon tag

Using Angular 8 material design, I am stuck at a point where I need to use both custom svg icons and built-in/regular material icons to the same mat-icon tag.

I am running a loop to display the menu with these icons, where-in for some menu items. I am using regular material and for some menu items, I have to use custom icons (svg).

Need something like:

<mat-icon svgIcon="menuIcon">{{menuIcon}}</mat-icon>

Upvotes: 3

Views: 4887

Answers (1)

Edric
Edric

Reputation: 26801

Typically, I would have 2 properties that represent a menu item's icon:

  • svgIcon which is the name of the SVG icon
  • icon which is the name of the CSS font icon

A menu item would be represented with the following interface:

export interface MenuItem {
  /** The menu item's title. */
  title: string;
  /** The menu item's SVG icon. Either this or the `icon` property should be used. */
  svgIcon?: string;
  /** The menu item's icon. Either this or the `svgIcon` property should be used. */
  icon?: string;
  // Other properties
}

Then I would conditionally show the appropriate <mat-icon> based on whether the svgIcon or icon properties are set:

<mat-icon *ngIf="item?.icon && !item?.svgIcon">{{ item.icon }}</mat-icon>
<mat-icon *ngIf="!item?.icon && item?.svgIcon" [svgIcon]="item.svgIcon"></mat-icon>

Alternatively, you could have an isSvgIcon property in your interface which represents whether the icon specified is an SVG icon:

<mat-icon *ngIf="item.isSvgIcon" [svgIcon]="item.icon"></mat-icon>
<mat-icon *ngIf="!item.isSvgIcon">{{ item.icon }}</mat-icon>

Upvotes: 2

Related Questions