Search code examples
javascriptsvgangularangular-ng-if

angular2: building svg icons with *ngIf adds nothing to DOM


I am using icoMoon to import some SVG icons.

The html I want to build using ngIf follows this pattern:

<div class="contactIcon">
    <svg class="icon icon-envelop">
        <use xlink:href="symbol-defs.svg#icon-envelop"></use>
    </svg>
</div>

So I'm exporting the icons array with icon and xlink properties:

export class NavigationComponent {
    icons = [{
            icon: 'icon icon-envelop',
            xlink: 'symbol-defs.svg#icon-envelop'
        },
        {
            icon: 'icon icon-facebook2',
            xlink: 'symbol-defs.svg#icon-facebook2'
        },
        {
            icon: 'icon icon-linkedin',
            xlink: 'symbol-defs.svg#icon-linkedin'
        },
        {
            icon: 'icon icon-mobile',
            xlink: 'symbol-defs.svg#icon-mobile'
        }];
}

and my html looks like this:

<div *ngFor="#i of icons" class="contactIcon">
    <svg [attr.class]="i.icon">
        <use [attr.xlink:href]="i.xlink"></use>
    </svg>
</div>

But when I inspect the page, nothing gets added, and no errors are shown in the console. All I see is this comment:

<!--template bindings={}-->

Can someone please point out what I'm doing wrong?


Solution

  • As far as I remember the workaround is to add the xlink:href attribute statically. Binding can modify such SVG attributes, only adding doesn't work. This is some underlying browser issue. Polymer suffers the same:

    <div *ngFor="#i of icons" class="contactIcon">
        <svg [attr.class]="i.icon">
            <use xlink:href="" [attr.xlink:href]="i.xlink"></use>
        </svg>
    </div>