Inline SVG Custom Element in Aurelia

A unique scenario popped up recently during a project I am building with Aurelia. I needed to cleanly be able to insert SVG images from a folder in my app and display them inline. Duplicating the SVG’s and inlining them was an option, or creating a custom element seemed like a better choice.

What I ended up coming with is the rather simple, but elaborate looking custom element which essentially replaces itself with the contents of an SVG.

import {bindable, containerless, customElement, inject, inlineView} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';

@containerless()
@inlineView('')
@customElement('inline-svg')
@inject(Element, HttpClient)
export class InlineSvg {
    @bindable svg;

    private el: HTMLElement;
    private http: HttpClient;

    constructor(el: HTMLElement, http: HttpClient) {
        this.el = el;
        this.http = http;
    }

    svgChanged(svg) {
        if (svg) {
            this.http.fetch(`/images/${svg}`)
                .then(response => response.text())
                .then(response => this.el.parentElement.innerHTML = response);
        }
    }

}

To use it, all you need to do is import the inline-svg class and then in your HTML view: you might want to change the path in the above example if you’re not always loading SVG’s from an images folder.

If you are not using TypeScript (like the above example) you will want to change it to be conventional Javascript instead of copying and pasting the above as is.