how to have matIconRegistry.addSvgIcon find the correct path

Viewed 733

I am using a custom svg as an icon for mat-icon and I can't get it to retrieve the icon correctly. It works if I put it in a folder next to the app folder (assets), but it doesn't work for other locations. I would like it to work specifically for an icon in the same folder as the icon.module and also for a folder that is a sibling of src. How can I achieve this? I am not sure why it doesn't work..

Here's icon.module.ts:

import { NgModule } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { MatIconRegistry, MatIconModule } from '@angular/material/icon';
@NgModule({
  imports: [MatIconModule]})
export class IconModule {
  private path = '../../script/icons';
  private path2 = '../assets/icons';
  private path3 = 'app/icons';

  constructor(
    private domSanitizer: DomSanitizer,
    public matIconRegistry: MatIconRegistry ) {
    this.matIconRegistry
      .addSvgIcon('base1', this.setPath(`${this.path}/bp.svg`))
      .addSvgIcon('base2', this.setPath(`${this.path2}/bp.svg`))
      .addSvgIcon('base3', this.setPath('src/app/icons/bp3.svg'));
      //.addSvgIcon('base', this.setPath('bp2.svg'));
  }
  private setPath(url: string): SafeResourceUrl {
    return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
2 Answers

You should include your other folders that can contain the svg icons inside your angular.json file in the projects.<your-project-name>.architect.build.options.assets array. This should help you solve your issue.

You can do it with the path:

.addSvgIcon('base4', this.setPath('assets/icons/bp4.svg')); 
Related