Angular 12: InlineSVG not working in production

1.9k Views Asked by At

I am using Angular 12 with ng-inline-svg. My .svg files are stored in the src/assets folder.

SVG location (TypeScript):

angleIconUrl = '${environment.assetsPath}assets/media/svg/icons/Navigation/Angle-double-left.svg';

( The environment.assetsPath contains either '/' or 'dashboard/' (dev assets and production assets)

Inline SVG (HTML):

<span class="svg-icon svg-icon-xl" (onSVGFailed)="fail($event)" [inlineSVG]="angleIconUrl"></span>

Instead of displaying the provided svg, I get the following error: No SVG found in loaded contents. When I try to use the same angleIconUrl on an img-tag with an src-attribute it works.

I already tried to add the svg files to the assets in my angular.json file but it does not work anyway.

"assets": [
    "src/favicon.ico",
    "src/assets",
    "src/.htaccess",
    "src/assets/media/svg/icons/Navigation/Angle-double-left.svg"
],            
2

There are 2 best solutions below

0
On

I had shared svg icons stored in the apps/shared/assets/icons/*. For angular 14 this worked:

in angular.json:

"assets":[
...
    {
      "glob": "**/*",
      "input": "apps/shared/assets/",
      "output": "assets"
    }
]

the path to the icon in html:

src="assets/icons/connection.svg"

and added svg mime type on the server:

mimetype.assign = (
  ".html" => "text/html",
  ".txt" => "text/plain",
  ".jpg" => "image/jpeg",
  ".png" => "image/png",
  ".js" => "text/javascript",
  ".css" => "text/css",
  ".svg" => "image/svg+xml"
)
2
On

asset bundle by default are copied to your /dist folder and not under {dist}/assets/ (dist varies as per your angular.json config property outputPath)

You can either remove the assets/ from the SVG url or update angular.json to have the following

"assets": [
    "src/favicon.ico",
    "src/.htaccess",
    {
        "glob": "**/*",
        "input": "src/assets",
        "output": "/assets/",
        "ignore": ["**/.DS_Store", "**/Thumbs.db", "**/.gitkeep"]
    }
]

To test whether it works or not, you can directly type http://localhost:4200/assets/media/svg/icons/Navigation/Angle-double-left.svg (change host and port as per your configuration) into browser address bar. If it loads then your configuration is correct. If not you need to try removing the assets/ from the path