Styling background images in Angular 4 with ngFor loop

I am having trouble with using background image URLs. I have an array of image URLs, how can I incorporate them into the background image URL?

<div class="col-lg-3 col-md-3 col-sm-6" *ngFor="let course of courses"><a>
    </a><div class="box"><a>
        <div class="box-gray aligncenter"  [style.backgroundColor]="course.imageUrl" >
        </div>
        </a><div class="box-bottom"><a >
            </a><a >{{course.name}}</a>
        </div>
    </div>
</div>

Answer №1

Check out this helpful resource on using dynamic background images in Angular2

// Avoid using style.backgroundColor 
[style.backgroundColor]="course.imageUrl"

// Instead, use style.backgroundImage
[style.backgroundImage]="'url('+ course.imageUrl +')'"

Answer №2

Many thanks for your responses, the accurate code is

[ngStyle]="{'background-image':'url(' + course.imageUrl + ')'}">

Answer №3

It is recommended to utilize the background property instead of backgroundColor

[style.background]="'url('+course.imageUrl+')'"

Answer №4

To achieve this, you can consolidate the URL path into a single variable. For instance:

bgImageVariable="www.domain.com/path/img.jpg";

In addition, there is another method:

second way
[ngStyle]="{'background-image': 'url(' + bgImageVariable + ')'}"

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

Converting objects to arrays in AngularJS and Ionic: A simple guide

In the scenario where I have an object structured like this: {first: "asdasd", second: "asdas", third: "dasdas", four: "sdasa"}, my objective is to convert this object into an array. if(values){ var first=values.first; var second=values.second; var ...

The CSS dropdown menu appears in a horizontal layout rather than vertical

** body { background-color: #9cb4c0; background-size: 100% 100%; } .div-1 { float: right; padding: 20px 10px; } h2 { text-align: right; ...

"Receiving an error message on Windows while trying to execute a package in Node.js: 'Cannot access property 'toString' of null

Utilizing the gulp and hercule packages on node.js to transclude some plain text files has been smooth sailing on Unix. However, encountering hiccups when running it on Windows. Colleagues are facing a specific error message while working on Windows: [13: ...

Progress bar displaying during Ajax request

I'm currently working on an Ajax request that uploads images to the Imgur API and I want to implement a progress bar to show users the upload progress. I found some guidance in this thread, but it seems to display only 1 and stop working. This is the ...

Sending an array of strings from an ajax call to an MVC controller

I'm encountering an issue where I have an array that I build up when a row is selected in my bootstrap data table. The problem arises when I try to pass this array from my view to the controller, which is supposed to fire up a partial view. Strangely, ...

Transform JSON data into a Java object with a modified format

I need to convert a JSON string representing an object into a Java object B with a different structure. My current approach involves creating a Java Object A that mirrors the JSON structure, using Jackson for JSON to A conversion, and Dozer with XML mappin ...

Aligning columns next to one another using flexbox in a centered manner

I am attempting to create a layout with 3 columns, but I want any extra columns beyond a multiple of 3 to be centered instead of aligned left. While I have made progress, the issue I'm facing is that the additional columns are not centered relative t ...

The request has encountered a 400 bad request error when using

I am encountering an issue with my web application. The frontend is built using React, the backend uses NodeJS, and the database is MongoDB. I have successfully implemented a registration form that posts data to the Node JS server via Axios and interacts ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

Unusual Vue syntax: deconstructing `state` from `this.$store` with a default value of an

While working on a pre-existing project, I came across some interesting notation in a Vue project utilizing Vuex: const { state = {} } = this.$store; const { orders = {} } = state; This code snippet appears to be creating a local object named "state" tha ...

Rspec failing to send emails after receiving Json post request

My specific query: context 'when valid information is provided' do describe 'refers to other users' do before(:each) do post '/shop/referrals', valid_referral_params ActionMaile ...

Arrange a div close to another div with the help of absolute positioning

My goal is to create a tooltip-like positioning for an element within the same container as another element. When clicked, this particular element will display a div containing a table. You can find the complete code here: http://jsbin.com/xihebol When s ...

The URL was updated, but the component failed to render. Only displayed correctly after the page was reloaded

Setting Up My Routing Module app-routing.module.ts { path: '', pathMatch: 'full', canActivate: [AuthGuard], component: HomeComponent, }, { path: 'profile', component: ProfileComponent, canActivate: [A ...

In Internet Explorer 11, the Content-Type setting is not functional and may cause issues with certain functionalities

My initial attempt to solve the issue involved using the method beginQuoteFileUnquoteUpload1, which created a proper boundary and Content-Type. However, upon receiving the file, I discovered that it was corrupted :( var formData = new FormData(); formD ...

Is it compatible to use Typescript version 2.4.2 with Ionic version 3.8.0?

Is it compatible to use Typescript 2.4.2 with Ionic 3.8.0? $ ionic info cli packages: (C:***\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.18.0 ionic (Ionic CLI) : 3.18.0 global packages: cordova (Cordova CLI) : not insta ...

Avoid changing the styling of the parent element when hovering over it

I am working on a comment box that allows for nested comments and is structured in the following way: <article class="comment"> Level 1 comment <article class="comment"> Level 2 comment </article> <article class="comment"& ...

Adjust the color as you scroll

It appears that the example provided changes the color from red to blue from the bottom, but I am looking for a solution that will change the color from top as I scroll. Can anyone help me achieve this effect using JavaScript? Here is another great referen ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Preventing Escape Keys in a JSON: Best Practices

I'm currently working on a dart / flutter application and I need to preserve special characters in the escape keys of the JSON server API response. How can I achieve this? For example: JSON response: {"\"\"exam ...

Is it possible for closures in JavaScript to cause stack fragmentation?

Could the stack become fragmented due to closures being allocated and not deallocated after a function returns? Closures are essentially stack frames that persist after a function completes execution, similar to a 'stack frame' on the heap rat ...