Search code examples
angulartypescript

Path working in scss file, but not in html template


I have the compilerOptions.paths in my tsconfig.json file set up as such:

    "baseUrl": "./",
    "paths": {
      "@/" : ["src/"],
      "@/*" : ["src/*"],
      "@app/*": ["src/app/*"],
      "@assets/*": ["src/assets/*"]
    }

I'm working in an Angular 18 project. In my home.component.scss file I have the following lines:

.main-callout {
    background: url('@/assets/img/bg.jpg') no-repeat center;
    background-size: cover;
    min-height: 646px;
}

The background image appears normally here. When I go to my navbar.component.html and use the following code:

    <a class="navbar-brand fs-1" href="#">
        <img src="@/assets/icons/Asset [email protected]" />
    </a>

the image is not found.

I found a similar issue that someone was having in vuejs and this is where I got some of my solution, but it didn't work for me

https://github.com/vuejs/language-tools/issues/589

Shouldn't the paths be recognized across the application once everything is compiled?


Solution

  • You can simply use a path without any prefix:

    <img src="assets/my-image.png">
    

    Or depending on how your base URL is set up, you might need to add a leading slash:

    <img src="/assets/my-image.png">
    

    But it shouldn't be necessary to use relative paths for assets.