Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

725
Vistas
Angular 2 img src in a relative path

The johnpapa Angular 2 style guide suggests a folder-by-feature approach. I get the idea, you can make self contained little angular components that can be reused.

So, I made a component I wanted to reuse in another project and put it in it's own folder. I also added an image I wanted this component to display to the same folder, so it's all self contained.

<img class="logo" src="logo.png"/>

But this tries to then load the image from root localhost:3000/logo.png.

I suppose this means I have to actually use the exact path to the image, but doesn't this undermine the whole idea of components that can be reused in other project by other people?

Suggestions on this?

Edit for clarification I am using the folder structure from the Angular 2 quickstart, meaning my root folder is:

app/
node_modules/
index.html
package.json
tsconfig.json

So, even if I use the path header/logo.png, it does not work. I have to do app/header/logo.png. This is effectively an absolute path, and in fact works equally as well if I add a leading slash: "/app/header/logo.png". Anything less than the full path breaks the link. Meaning if someone wanted to reuse this they would have to have the exact same folder structure.

I guess this is just how it works, I'm only just learning Angular 2, but in my mind I should be able to load assets from within a components folder just like I can with the template or css

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

I am using webpack and have been able to overcome this issue by requireing the image in the component as a variable and using this in my template.

This is because during the bundling phase webpack will load the resource and store the correct URL and calling require at runtime will get this correct URL to pass to the template.


Example

Using the following directory structure

app/
    header/
        header.component.ts
        header.component.html
        assets/
            logo.png
...

header.component.ts

...
@Component({
    selector: 'header',
    templateUrl: './header.component.html', // Auto required by webpack
})
export class HeaderComponent {
    private LOGO = require("./assets/logo.png");

    constructor() {};
}

header.component.html

<div>
    <img [src]="LOGO" />
</div>

Admittedly this binds the component and template but the require needs to be in the component so that webpack is able to analyse and load it when bundling.


With this approach I have packaged my module using npm and installed and used it in another project - which also uses webpack.

I am yet to test with SystemJS.

over 4 years ago · Santiago Trujillo Denunciar

0

@David's solution is slightly outdated given that now angular2 can be upgrade, it works for anular 2/3. For angular 4 and above it would throw require not found error, this is how i modified it,

header.component.ts

...
declare var require: any;

@Component({
    selector: 'header',
    templateUrl: './header.component.html', // Auto required by webpack
})
export class HeaderComponent {
    private LOGO = require("./assets/logo.png");

    constructor() {};
}

header.component.html

<div>
    <img [src]="LOGO" />
</div>
over 4 years ago · Santiago Trujillo Denunciar

0

I would solve this problem by splitting the src path into 2 parts, like this:

<img class="logo" [src]="(imgPath + imgFileName)" />

then, inside the component definition, you set:

@Input() imgPath:string = "app/header/";
imgFileName:string = "logo.png";

By using the @Input() decorator, the imgPath variable can be seen externally, so that in case you move the component into another place you can set a different path, making the component reusable.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda