Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Angular 2 load an SVG image?

Tags:

angular

svg

I tried this code in an Angular 2 template:

<ul class="products">
  <li *ngFor="#p of products">
    <svg width="200" height="100" xmlns="http://www.w3.org/2000/svg"
         xmlns:svg="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink">
         <g>
            <title>{{p.Name}}</title>
            <image xlink:href="http://somewhere.com/{{p.Picture1}}"
                   id="svg_21" height="176.731579" width="117" y="28" x="32" />
        </g>
    </svg></li></ul>

And got the error:

 EXCEPTION: Template parse errors:
 Can't bind to '@xlink:href' since it isn't a known native property 
 <image [ERROR ->]xlink:href="http://somewhere.com/{{p.Picture1}}"
        id="svg_21" height="176.731579" widt"): AppComponent@13:37

I tried to use this, which is definitely on the right path:

attr.xlink:href="http://somewhere.com/{{p.Picture1}}"

but in using that, I instead get an error of cannot find my-app.

like image 501
Zachary Scott Avatar asked Dec 17 '25 17:12

Zachary Scott


1 Answers

Seconds after posting the question, I found the answer:

<image *ngIf="p.Picture1" attr.xlink:href="http://somewhere.com/{{p.Picture1}}" />

Apparently if p.Picture1 is empty, it invalidates html or SVG more likely in such a way that my-app is not found, which follows.

like image 102
Zachary Scott Avatar answered Dec 19 '25 06:12

Zachary Scott