Md Nuhel
Md Nuhel

Reputation: 85

How to set the background image with Angular?

<div class="class1">
    <app-home></app-home>
    <router-outlet></router-outlet>
</div><div class="class1">
    <app-home></app-home>
    <router-outlet></router-outlet>
</div> <!-- This is the home.component.heml -->


.class1{
    background-image: url(/Users/md.nuhelnawazchowdhury/Desktop/Shoppie/andalib/src/assets/img/Shoppie1.jpeg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

I can't get the home page to show the background image. The files above are app.component files.

Upvotes: 1

Views: 11092

Answers (3)

Meghshyam Sonar
Meghshyam Sonar

Reputation: 301

Try using a url in single quotation for a url as shown below!

<div class="class1">
    <app-home></app-home>
    <router-outlet></router-outlet>
</div><div class="class1">
    <app-home></app-home>
    <router-outlet></router-outlet>
</div> <!-- This is the home.component.html -->


.class1{
    background-image: url('/Users/md.nuhelnawazchowdhury/Desktop/Shoppie/andalib/src/assets/img/Shoppie1.jpeg');
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

But for the best practice of developing an angular app I would recommend to create a separate folder for images inside an asset folder that would be the best way to track and make an application clean.

Upvotes: 2

Elmehdi
Elmehdi

Reputation: 1430

First start by putting your images inside assets folder.
Assets folder is automatically created by Angular CLI, when you create a new project.
Now it depends on where you wanna use the background image.
If you are in app folder you can do somthing like this:

background-image: url(../assets/Shoppie1.jpeg);

if you are deeper, say you created a component in its own folder, you will have to do something like:

background-image: url(../../assets/Shoppie1.jpeg);

I created this github demo if you wanna see how it is done: link

Upvotes: 4

B45i
B45i

Reputation: 2602

Yout path should be /assets/img/Shoppie1.jpeg

 background-image: url("/assets/img/Shoppie1.jpeg")

Open Developer tools > Network tab and check if the image is getting downloaded while the app is loaded.

Upvotes: 2

Related Questions