Angular: Using custom made SVG icons through Angular Material

Stefanos Kouroupis - Oct 22 '19 - - Dev Community

This is a tiny, but useful post that will demonstrate how to create a service that registers custom svg icons in order to use them through the mat-icon component.

Step 1. I place all my icons under assets/svg/icons
Step 2. I create an string enum with all the icon names i.e. (you could just have a string array but I like the idea of using an enum)

export enum Icons {
    Close = 'close',
    Done = 'done',
    Edit = 'edit'
}

Step 3. I create my service. Which simply iterates all values in my string enum and registers them again the MatIconRegistry. bypassSecurityTrustResourceUrl simply bypass the security checks and trusts the svg file (make sure the svgs are to be trusted).

@Injectable({
  providedIn: 'root'
})
export class IconService {

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

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

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

Step 4. Then simply on the app.component.ts ngOnInit call the registerIcons function

  constructor(private iconService: IconService) {
  }

  ngOnInit() {
    this.iconService.registerIcons();
  }

Step 5. Use them anywhere in the application

    <mat-icon svgIcon="edit"></mat-icon>
. . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player