Angular 2 img src in a relative path

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)