angularnpmangular-librarynpm-package

How to integrate icons into an angular library?


I would like to integrate an SVG icons into my angular library's template, and I have the following questions?

How can I achieve this, please?


Solution

  • Where should the /assets folder be located?

    In an Angular library, the recommended location for the /assets folder is under /src, not /src/lib. This ensures that the assets are bundled correctly when the library is built and consumed in applications.

    Structure: projects/src/assets/icons/icon.svg

    ng-package.json and/or angular.json Modifications

    angular.json

    {
      "projects": {
        "library-name": {
          "architect": {
            "build": {
              "options": {
                "assets": [
                  {
                    "glob": "**/*",
                    "input": "src/assets",
                    "output": "assets"
                  }
                ]
              }
            }
          }
        }
      }
    }
    

    ng-package.json

    {
      "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
      "assets": [
        "src/assets"
      ]
    }
    

    In the component templates

    Use a relative path like this

    <img src="assets/icons/my-icon.svg" alt="My Icon">
    

    Use relative paths ensures that the assets are packaged with the library and work seamlessly when the library is consumed in different environments.