I'm currently building an Angular application where I'm trying to load in a customer's logo based on a config found elsewhere.
I'm trying to load this file into my home.component.html
I created a "CustomerService" which has a function getLogo() which in itself returns the customer's logo's path.
My folder structure is as follows:
FOLDER STRUCTURE IMAGE
The assets folder holds the images, and the HTML found below is found in home.component.html
I know that "../../" isn't the way to go, so my first question is how I'd be able to fix that.
I've created the following HTML structure:
<img src="../../assets/timeblockr-logo.png" />
<img [src]="customerservice.getLogo()" />
And the CustomerService's getLogo function returns the following:
getLogo() {
return "../../assets/timeblockr-logo.png";
}
Turns out I had to use:
getLogo(): string{
return require("../assets/timeblockr-logo.png");
}
Special thanks to @Niladri for the solution to this issue!
Your image source should be without ../../
. The image paths are relative in the output folder. Just change to this:
<img src="assets/timeblockr-logo.png" />
<img [src]="customerservice.getLogo()" />
And your function should be:
getLogo(): string {
return "assets/timeblockr-logo.png";
}
As per your comments, you need to change your "assets"
entry in .angular-cli.json
to this:
"assets": [
"assets",
"favicon.ico",
{
"glob": "**/*",
"input": "./assets/images/",
"output": "./assets/images/",
"allowOutsideOutDir": false
}
],
Webpack uses url-loader
to load images from your angular project that comes with extension .png,.jpg
etc . Take a look at the below code from the url-loader
repo in github https://github.com/webpack-contrib/url-loader
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
}
]
}
}
it looks for image files with the above extensions. But we need to use require
statement to the actual image path for the Webpack to understand the path of the image so that it can pick them up. This is required in .ts
/ typescript files while using the path of the image as a variable or returning the path value from a method . The first image tag
<img src="../../assets/timeblockr-logo.png" />
was working because Webpack uses html-loader
for .html
files, which automatically replaces src attribute values on image tags with the bundled image URL.
So your getLogo()
method should be like below
getLogo():string {
return require("../assets/timeblockr-logo.png");
}
Change <img [src]="customerservice.getLogo()" />
To <img [attr.src]="customerservice.getLogo()" />
Read more about Attribute Binding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With