Angular 2 img src in a relative path

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.


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.