1

I'm running into a weird svg issue with Angular2's PathLocationStrategy.

The svg in my html template is like

<svg class="bell__icon" viewBox="0 0 32 32">
    <use xlink:href="#icon-notificationsmall"></use>
</svg>

In my bundled svg file, the corresponding icon is like

<svg xmlns="http://www.w3.org/2000/svg" style="position:absolute; width: 0; height: 0">
    <symbol viewBox="0 0 32 32" id="icon-notificationsmall">
        <path
        d="M26.2 22.5V12.4c0-4.9-3.4-9.2-8.3-10.2V2c0-1.1-.9-2-2-2-1.1-.1-2 .9-2 2v.3c-4.7 1-8.2 5.2-8.2 10v10.2L2 29h9.8c.6 1.7 2.3 3 4.2 3 2 0 3.6-1.3 4.2-3H30l-3.8-6.5zm-18.5 0v-10c0-3.9 2.7-7.3 6.6-8 1-.1 2.2-.1 3.2 0 3.9.7 6.6 4.2 6.6 8v10l2.4 4.2H5.4l2.3-4.2z"></path>
    </symbol>
</svg>

This svg is on the header component which will be showing on top of each page.

The svg gets displayed correctly after the home page is loaded and also displayed if I navigate back and forth through links, however, it disappears after reloading/refreshing the page.

When I inspect the svg, it's always there even if it's not showing up.

I do have a <base href="/"> in my index.html file and it seems that this answer solved a similar issue in Angular1.

So, I tried below in the corresponding .ts file

import {LocationStrategy} from '@angular/common';
private fullPath:any;
constructor(private location:LocationStrategy) {
  this.fullPath = (<any>this.location)._platformLocation.location.href;
}

and changed the html template like

<svg class="bell__icon" viewBox="0 0 32 32">
    <use xlink:href="{{fullPath}}#icon-notificationsmall"></use>
</svg>

But I got error EXCEPTION: Error: Uncaught (in promise): Template parse errors: Can't bind to ':xlink:href' since it isn't a known native property.

By the way, my original code works well under HashLocationStrategy.

Community
  • 1
  • 1
Bing Lu
  • 3,232
  • 7
  • 30
  • 38

1 Answers1

1

Try

<use attr.xlink:href="{{fullPath}}#icon-notificationsmall"></use>

or

<use [atrr.xlink:href]="fullPath#icon-notificationsmall"></use>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Wow! It works! Thanks for your quick and amazing answer! – Bing Lu Jul 25 '16 at 20:30
  • SVG elements don't have properties that are reflected to attributes as other elements (and vice versa). Angular2 binds to properties by default. You need to use attribute binding explicitely. http://stackoverflow.com/questions/6003819/properties-and-attributes-in-html – Günter Zöchbauer Jul 25 '16 at 20:31