skip to Main Content

I cant add my image to the web app, when i try to load a image from a url like

<img src="http://website/img.png">

works fine but when i try to open a image on my project doesn’t load

<img src="/assets/img.png">

i try with diferent images and change the path so many times to the public or other paths

2

Answers


  1. Make sure you have baseHref set in your project.

    <base href="/">
    

    Then you create an assets folder and make sure you add it in the angular.json inside the assets array.

      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:application",
          ...
          "options": {
            "assets": ["src/assets"],
            ...
    

    Finally, you can import and use it.

    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <img src="/assets/download.jpg"/>
      `,
    })
    export class App {
      name = 'Angular';
    }
    
    bootstrapApplication(App);
    

    After doing these changes, I had to restart my application for the changes to take effect.

    Stackblitz Demo

    Login or Signup to reply.
  2. I noticed that for new Angular 18 projects they’ve moved the default assets location in the repository from /assets to /public and the output in the final build from /assets to /.

    So if you don’t want to change your angular.json you should put your img.png in the /public folder in your repository.

    In your template you should link to /img.png:

    <img src="/img.png">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search