When running a web application with ng serve in Angular, the use of relative paths in component CSS for background images may not

I have a situation where I need to assign two different background images to two div elements with IDs div1 and div2. These images have the same name but are located in different folders. In order to achieve this, I set up my configuration as follows:

app.component.html :

<div id="div1"></div>
<div id="div2"></div>

app.component.css:

I used the background-image property with different paths for each div.

#div1 {
  background-image: url('../assets/images/videos/back.jpg');
  /* other styles */
}

#div2 {
  background-image: url('../assets/images/blogs/back.jpg');
   /* other styles */
}

Problem :

When serving the app using ng serve, both div elements display the same background image.

Please note that the path to both images is different but the name is the same.

Reason :

Upon checking the browser's developer tools, I noticed that the style is being applied as follows:

#div1 [_ngcontent-c0] {
    background-image: url(back.jpg);
    /* other styles */
}

#div2 [_ngcontent-c0] {
        background-image: url(back.jpg);
        /* other styles */
}

This means that instead of

url('../assets/images/blogs/back.jpg')
, it is just showing url(back.jpg) - without the relative path, causing both div elements to show the same image in the background.

Question :

Is this expected behavior for Angular? If not, what am I missing here?

Answer №1

Paths in CSS should be relative to the base URL rather than the component within the src directory. Ensure to remove any leading .. from the path but keep the leading slash:

#div1 {
  background-image: url('/assets/images/videos/back.jpg');
}

#div2 {
  background-image: url('/assets/images/blogs/back.jpg');
}

Through testing, it is evident that when utilizing a path relative to the source code, the CLI generates a duplicate of the image being referenced and places it at the root of the dist folder. As a result, the structure of the dist folder will appear as follows:

/dist
  // The CLI created this image 
  // which your component references, however,
  // you intend to reference images in the
  // assets folder.
  back.jpg
  /assets
      /images
          /videos
              back.jpg
          /blogs
              back.jpg

Answer №2

To make mine function properly, I had to implement an inline style

<div id="banner" style="background-image: url(./images/picture.jpg)">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What to do when calling disabled() on a FormControlName causes all form fields to become invalid?

While working with a reactive form, I have observed that setting a formControlName to disabled() can cause the entire form to become invalid. Is there a way to ensure the form remains valid even after disabling a control? console.log('Before:' ...

The Angular Material Checkbox fails to accurately reflect the one-way bound value

When working with one-way data binding and checkboxes, there is an issue where the check mark on the checkbox does not accurately reflect the bound value. This results in the checkbox being able to be checked or unchecked independently of the binded value. ...

What is the best way to transfer data to the server in a loop without encountering synchronization issues?

I am working with an array of products in typescript (in angular) and my goal is to update their prices in the database using http calls. The way I currently insert them is as follows: array.foreach(element=>{ this.product.price=element; this.myS ...

Testing private methods in Angular

I have developed a unique Queue manager that utilizes RxJs observables to execute tasks sequentially. Now, I am facing the challenge of testing this functionality as all the methods I need to test are private. The public interface of my Queue manager cons ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

The art of browser manipulation: Javascript positioning

My issue revolves around the positioning of a Hello Bar. The CSS is set to relative, which has caused the entire site to be pushed down. To address this issue, I have implemented the following JavaScript function: <script language="javascript"> $( ...

I find it difficult to customize columns in grid template areas

I am having trouble adjusting the width of my header's columns to be 24vw, 24vw, 4vw, 24vw, and 24vw respectively. Despite specifying these widths, the browser is rendering all columns with equal width. Specifically, I am unable to change the width of ...

Struggling to reach the same level of bundle optimization with webpack + angular when compared to angular-cli

I am currently facing an issue with two Angular projects that I have. One is developed using angular-cli, while the other one is built with Webpack and utilizes @ngtools/webpack. Both projects are based on Angular 7.1.4 and @angular-devkit 0.13.5. The code ...

Providing the module with the URL

How can I retrieve the URL within a module? module.exports = function(app, Reviews, Anon, User, url){ var url = url; console.log("url", url)// url is undefined how to get url function postHandler(req, res){ } app.post("/individual/"+ u ...

Creating personalized error messages for responses in serverless computing platforms allows for a more

I have been exploring the Node.js serverless V2 framework and discovered that callbacks only accept Allow, Deny, and Unauthorized as parameters. I am using a custom authorizer for resource protection but struggling to send a custom error message via callba ...

Unusual margin glitch discovered in Chrome version 9

Encountered a strange issue with Google Chrome 9: A left-margin for an input element is specified but Chrome fails to apply it upon page load. Oddly enough, when I toggle the specific declaration off and then back on using Developer Tools, the margin is f ...

What is the best way to structure an array for JSON transmission between Express/NodeJS and ReactJS?

I have a query similar to the one posted on POST array of objects to REST API. However, I need a different formatting for my answer. My dataresults array contains Objects like: [ { reviewID: 5, TextComment: 'lol2314'}, { reviewID: 4, TextC ...

Tips for adjusting the size of your logo for the mobile edition of your WordPress site

I have been attempting to adjust the size of our website's logo ( ) for mobile viewing, but so far no code has proved effective. I've tested various iterations like the one below without success: @media (max-width: 360px) { .site-branding ...

What strategies prove most successful in resetting a reactive angular form effectively?

I'm currently working with Reactive Forms using Angular Material inputs (mdInput) that are initialized with FormBuilder in the following way: contactForm: FormGroup; this.contactForm = this.fb.group({ name: ['', [Validators.required, Val ...

Alter the hue of a component upon being clicked

Seeking help to modify the color of my menu elements upon clicking on the "center" or "right" containers (reverting back when clicked again). Currently, the three lines in my menu are white, but I desire them to turn red when either of these containers is ...

Ways to retrieve the ID of the clicked element from the child up to the parent

I currently have a Parent component and a Child component. The Child component contains inner elements called notes, with "delete" being one of them. My goal is to have the Child component return an ID to the Parent component when the delete element is cl ...

Discovering an already existing table in Mongo Atlas with Mongoose - a detailed guide

Having already created multiple tables and stored data in them using Mongo Atlas, I am now looking to utilize Mongoose for searching the data within those tables. Do I have to define schemas and models for the tables I have already set up in Mongo Atlas? ...

Unable to start React Native CLI Project Initialization

I recently started using React Native CLI for my CRUD project. After initializing the project and running 'npx react-native run-android' inside the project folder, I encountered the following errors: npx react-native run-android info Starting JS ...

What are the steps to take in order to publish an npm package for testing purposes?

Is there a way to release an npm package with a prerelease version in order to conduct testing without impacting other users who execute npm install <package-name>? Existing attempts setting the version to v1.0.0-0 and publishing have not yielded th ...

I'm experiencing an issue where the line-height css property is not functioning as expected in a JEditorPane. Can anyone provide

Having an issue with the line-height attribute in a JEditorPane. It seems to be ignoring it, even though the font and color attributes are working fine. I've checked the HTML in Firefox and it looks good. Does anyone have any idea what might be wrong? ...