8

Am building a project on Angular and this project will have lots of images as part the design. Am wondering if it is possible to keep images used by each component within the component instead of having to fetch each image from the assets folder.

I want to know if it is possible to configure Angular to house and serve images used by a component within that component.

See picture for clarification:

Sample App

3 Answers 3

2

Assets Contains image files and other asset files to be copied as-is when you build your application.

But Yes, you can!

But for this you need to manually require each image in your component file and use dyanmically in template like this -

declare var require: any
myImage = require('./myImage.png');

<img [src]="myImage" />

As by default Angular CLI has a configuration for static data such as Images/Fonts/Css files etc from assets folder.

But if you want to use some static data outside from there you need to require like above mentioned.

PS: Not sure whether angular takes all static data at the time of build such as image at the component level. But should work in ng serve

Sign up to request clarification or add additional context in comments.

4 Comments

I don't think require with image will work in Angular.
@SureshKumarAriya I have tried this on my local project before posting it as answer
@PardeepJain I tried it but couldn't get it to work on mine...any more help will go a long way pls.
@SureshKumarAriya Not sure about stackblitz, But Tested on local project on my machine, Have you tried there?
0

Yes. You can put the images in the component folder and access the same from component file. Just you have to give the correct path of the image file in component or HTML file

Example: In component file directly access the file by the name without any folder path fileName.jpeg

1 Comment

Have you tried this? I am not sure because by default in angular cli path is set for assets folder for static data say images, some css files fonts etc
0

many thanks @PardeepJain I have been able to get it to work following your direction.

But this is what I did in case of others:

declare var require: any;
declare var img: any;
export class IndexNavComponents { enter code hereimg= require('./myImage.png'); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.