STYLE SWITCHER

Using an SVG sprite icon system in Angular

Whether it’s icon fonts or SVG sprites you use as icon sets in your application is your decision. However, we’ll cover some advantages that SVG sprites have, but most importantly how you can implement them in Angular.

Create a new component file called: svg-icon.component.ts, and add the following content.

import {
Component,
Input
} from '@angular/core';

@Component({
selector: 'svg-icon',
template: `
<svg>
// SVG elements don't have properties, therefore attribute binding is needed
// https://stackoverflow.com/a/35082700
<use attr.xlink:href="assets/symbol-defs.svg#{{icon}}"></use>
</svg>
`
})
export class SvgIconComponent {
@Input() icon: string;
}

Next, register our new component to the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { SvgIconComponent } from './svg-icon.component';

@NgModule({
declarations: [
AppComponent,
SvgIconComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}

Finally, update app.component.ts so it consumes our newly created component.

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
styleUrls: ['./app.component.scss'],
template: `
<svg-icon icon="icon-images" class="icon"></svg-icon>
`
})
export class AppComponent {
}

Create a svg-icon.component.scss file, and replace the content with the following.

:host {
display: inline-block;

svg {
display: inline-block;
all: inherit;
}
}
Source Code

Recent Article

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Keep your skills sharp, get informed.

    Subscribe to our mailing list and get interesting stuff and updates to your email inbox