Setting the background image of a div in my Angular application by utilizing the value returned from an API call

I'm currently working on a movie search application where I need to set an image as the background of a div. The URL for this background image is fetched from an API call.

Here is what I have tried so far:

<div *ngFor="let movie of movies.results">
  <div
    class="thumbnail" style="background-image: 
    url(https://image.tmdb.org/t/p/w500{{movie.poster_path}})"
  >
    -- id: {{ movie.id }} -- name: {{ movie.title }}
  </div>
</div>

Upon trying the above code, I received a warning message:

WARNING: sanitizing unsafe style value background-image: url(https://image.tmdb.org/t/p/w500/fw02ONlDhrYjTSZV8XO6hhU3ds3.jpg)

Unfortunately, the image did not display as expected.

Next, I attempted using this line of code in hopes of resolving the issue:

this.sanitizer.bypassSecurityTrustUrl(`
https://image.tmdb.org/t/p/w500"${this.movies.results[0].poster_path}
`);

However, I still encountered the same problem.

I then experimented with the following code snippet:

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

But despite my efforts, the image failed to load.

If anyone has any suggestions or solutions to help me overcome this challenge, I would greatly appreciate it!

Answer №1

It seems like you were on the right track by utilizing the DomSanitizer and bypassSecurityTrustUrl. However, I suggest trying a similar approach but using bypassSecurityTrustStyle instead to possibly resolve the issue.

<div *ngFor="let film of films.list">
  <div
    class="thumbnail" [style.background-image]="getSecureStyle(film.image_path)"
  >
    -- id: {{ film.id }} -- title: {{ film.name }}
  </div>
</div>

getSecureStyle(link: string) {
  return this.sanitizer.bypassSecurityTrustStyle('url(\'' + link + '\')');
}

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

Struggling with getting the Bootstrap Carousel to switch between slides?

I'm facing a challenge in creating a functioning carousel with Bootstrap. I've utilized a template for this purpose, but the issue lies in the slides not transitioning correctly when I click the arrow buttons to move to the next or previous slide ...

Angular 7 Material: How to ensure that mat-select autofill does not persist the source value after it has been cleared on keypress

My goal is to have complete keyboard control over this component. This means ensuring proper focus on tab press and resetting the temporary item when necessary. After adding the temporary item to the list, it should refocus on the first line item field. O ...

Utilize ngModel within the <p> element in Angular 8

Here is some HTML code for displaying card information: <div class="col-md-4" *ngFor="let card of allCards"> <p class="card-text">Card Color: {{card.color}}</p> <button type="button" class=" ...

Changing the Angular 5 ng-bootstrap Modal Dialog template dynamically in real-time

I'm currently developing a modal dialog that requires the ability to dynamically change the templateURL. The code shown is the default template, but I need to be able to swap it out dynamically. I'm unsure of how to achieve this, as the templateU ...

Encountered an error while trying to upgrade Angular from version 9 to 10: The package '-e' is not recognized as a dependency

Anyone else run into this problem while upgrading an Angular app from version 9 to 10? The error message reads: ng update @angular/core@10 @angular/cli@10 I tried searching online but couldn't find any solutions that addressed my specific issue. ...

Using jQuery to remove the 'active class' when the mouse is not hovering

I recently came across this amazing jQuery plugin for creating slide-out and drawer effects: However, I encountered a problem. I want to automatically close the active 'drawer' when the mouse is not hovering over any element. The jQuery plugin c ...

Can you help me identify the reason behind a page displaying a temporary horizontal scrollbar?

While browsing the following page in Google Chrome: A horizontal scrollbar appears briefly during page load. It seems that something hidden below the fold is causing this issue, but I haven't been able to identify the exact cause. EDIT:- Watch a v ...

How can I stop my browser from recalling text field data?

Similar Question: Is there a W3C compliant method to disable autocomplete in an HTML form? How can I stop a browser from remembering the text field's content? The issue arises when the field has a value like 100, followed by a currency symbol suc ...

PHP bug causing inaccuracies in output results

I've written a PHP script to determine a student's final grade, taking into account weight and target grades. However, the output value it generates is incorrect. Below is my current PHP code: <?php $numassignments = isset($_GET['numass ...

Tips for Dealing with Empty Rows in Arrays

How can I remove rows from an array in Alasql where all key values are null? Here is the array data: [ 0:{Name:"ABC1",No:5,BalanceDue:5000,Notes1:null,Notes2:null,CurrencyId:"2",Date:"06/01/2018"} 1:{Name:"ABC2",No:6,BalanceDue:6000,Notes1:null,Notes2: ...

Retrieve the recordset value in order to automatically mark a checkbox as selected

I am having an issue with a checkbox named "cbBatch" on one of my pages. After checking the box and submitting the form, "cbBatch" is stored as 1. On the following page, I want cbBatch to be automatically checked if the value in the corresponding database ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

Tips for preventing control click events from interfering with modal dialog interactions

From what I understand, when I open a modal dialog in jQuery, all input controls will be disabled. However, I am still able to click on buttons, divs, and other controls. Is there a way in jQuery to disable all interactions once the modal dialog is opene ...

Testing the subscription feature with unit tests

I am currently testing the reception of an array of people to ensure consistent response types, allowing for detection of any changes in the object from the back-end. Interface Definition: export interface People { peopleDtos: [{ id: number, ...

A straightforward development and production build to incorporate HTTPS for a static website created with React and Express

Is there a straightforward method to create a static web page and Node backend where the Node server runs in HTTPS during development but not in production? How can the static web page point to https://localhost/foo in dev mode, and simply /foo in producti ...

jQuery's AJAX feature fails to identify the newly modified div classes

For my new website, I am developing a simple checklist feature. To handle the check and uncheck requests from users, I'm using jQuery's $.ajax() function. Whenever a user clicks on the check or uncheck buttons, jQuery retrieves the validation tok ...

Is it possible to use the Stop Button on the HTML5 Audio Tag to halt a live MP3 stream

Is there a way to add a stop button as well? Currently, I have play and pause buttons, but the stop function doesn't truly clear the music buffer in the browser; it just stops playback without resetting to the beginning. This is fine for MP3 files but ...

Is it possible to single out the final element having a specific CSS class in the absence of a parent container?

I have the following elements dynamically rendered in an HTML file. <div class="vehicle"></div> <div class="vehicle"></div> My requirement is to add a style float:right inside CSS class vehicle for the second el ...

Error: Unable to locate loading.gif file within the Angular library

In my current setup, I have a monorepo that includes a standard Angular application and an Angular workspace with a library at the same level as the app. After configuring the main app to recognize the library, I am able to use the components without any ...

Azure Function (.NET 7, v4) encountering Cross-Origin Resource Sharing problem

I am experiencing a CORS problem with my Azure function written in C# using .NET 7. It is being called from my Angular application. Interestingly, the same function works fine when called from Postman with the same request body as the Angular application. ...