Search code examples
angularsvgangular-libraryng-packagr

Use relative path for svg in Angular Library Component


I created a custom Library with Angular Cli. It has the following structure:

 - dist
 - projects 
    - customLib
        - src
            - assets
                - icons
            - lib
                - button

The button component gets as Input() the name of the svg icon that will be displayed inside the button:

  import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'lib-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss']
 })

export class ButtonComponent implements OnInit {
svgIconUrl: string;

constructor() {
}

ngOnInit() {
  if (this.icon) {
    this.svgIconUrl = '../../assets/icons/' + this.icon + '.svg';
  }
}}

html of button component:

<button>
   <div *ngIf="svgIconUrl">
    <svg-icon [src]="svgIconUrl"></svg-icon>
   </div>
</button>

I made a script which copy all icons (stored in src/assets/icons) and paste it inside dist folder. All this is working fine. Then, I published my library on bitbucket and I installed it in another Angular Application. The Library is imported correctly, but angular-svg-icon cannot find the svg because it is taking the svg in localhost:4200/#/assets/icons/myicon.svg

And of course it doesn't find the svg, because it is inside the library, so it is inside the "node_modules" folder. How can i force the button component of Library to take the svg inside the Library, so with a relative path?

this is the html, in the Angular App (which is importing and using the Library) where I use the button:

    <lib-button icon="icon-magic"></lib-button>

Solution

  • I've faced the same problem, and the only decision I've found is to include to ng-package.json in "lib" section "cssUrl" param:

    "lib": {
       "entryFile": "src/public-api.ts",
       "cssUrl": "inline"
     },
    

    According docs, it allows embed assets in css file using data URIs.