Register multiple svg icons from single svg file mat-icons

Viewed 837

This is the current icon service to register custom svg icons

export class IconService {
  constructor(
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer
  ) {}

  public registerIcons(): void {
    this.loadIcons(Object.values(Icons), '../assets/icons');
  }

  private loadIcons(iconKeys: string[], iconUrl: string): void {
    iconKeys.forEach((key) => {
      this.matIconRegistry.addSvgIcon(
        key,
        this.domSanitizer.bypassSecurityTrustResourceUrl(
          `${iconUrl}/${key}.svg`
        )
      );
    });
  }
}

Instead of loading the svg per each file, I put all the svgs into a single folder with this kinda syntax

my-icons.svg

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <symbol id="icon_id">
  ...
  </symbol>
</svg>

I want to be able to do something like:

...
    this.matIconRegistry.addSvgIcon(
        key,
        this.domSanitizer.bypassSecurityTrustResourceUrl(
          `${iconUrl}/my-icons.svg#${key}`
        )
      );
...

where each key is an id pointing to the <symbol id="icon_id">... in the my-icons.svg file

1 Answers

You can't do what You want but You can do this:

this.matIconRegistry.addSvgIconSet(
      this.domSanitizer.bypassSecurityTrustResourceUrl("icon_url.svg")
    );

You will use icons by id like this:

<mat-icon svgIcon="id_of_symbol_in_icon_url_svg_file"></mat-icon>
Related