Sameer
Sameer

Reputation: 5188

file-loader does not work with dynamic url in angular

Does file-loader ignore dynamic url?

// app.component.html
<img src="../assets/flower.jpeg" alt="Flower" width="100px">
<img src="{{assets}}flower.jpeg" alt="Flower" width="100px">
// app.component.ts
export class AppComponent {
  assets = '../assets/';
}

As you can see I have 2 images in html. The first image is displayed as expected, but the second one does not work.

The first image is generated and image url in html is also changed, whereas second image url is not hashed.

//eg:
<img src="./assets/b16683a9edb6ebf57d144f8b86cb163e.jpeg" alt="Flower" width="100px">
<img src="../assets/flower.jpeg" alt="Flower" width="100px">

Here is the git repo to reproduce issue, Run npm i && npm start

Upvotes: 1

Views: 597

Answers (4)

vi calderon
vi calderon

Reputation: 196

You need to bind like this

<img src='{{ "assets/images/" + wonder.id + ".jpg" }}' />

[] is not compatible with {{ }}.

Upvotes: 0

Sergey Mell
Sergey Mell

Reputation: 8040

In your particular case - yes, your path is simply ignored as an incorrect one. However, if your change it to ./{{assets}}flower.jpeg (just for example) you'll get an error

ERROR in Cannot find module './{{assets}}flower.jpeg'

Why is that happen? {{assets}} is an Angular binding and the exact value will be known only during the application run not during the building process. So the only way this path can be handled during the building process is just like it is and consequently, file-loaded cannot find any file on this incorrect path and gives you an error.

I hope I've explained the issue pretty clear. However, feel free to ask more questions in the comments if some details are not clear for you.

Upvotes: 3

Rajantha Fernando
Rajantha Fernando

Reputation: 308

Do like this, <img [src]="assets+'flower.jpeg'" alt="Flower" width="100px"> Change path to asset as follows assets = 'assets/';

Upvotes: 0

vi calderon
vi calderon

Reputation: 196

I made this example and it works The fisrt is an html with the code html The second is the .ts I wrote a variable in the ts called path where I put the url of my image then I use binding in the property src in the html and I send the variable path. So when I click the button called 'change' the image change dynamically

Upvotes: 0

Related Questions