Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example:

<div [style.background-image]="profileImage" ></div>

In the TypeScript file:

We declare private profileImage: any; and use DomSanitizer for security.

Fetching photo from service:

We set this.profileImage using bypassSecurityTrustStyle to display the fetched image securely.

The binding issue:

After checking Chrome Dev tools, it seems that the photo is not being downloaded. On page refresh, everything works as expected, but the image should load when the value is initially set by the service. Attempts with ngStyle also failed.

To view the problem on Plunkr, click here.

Answer №1

Your code has been modified to ensure functionality:

@Component({
  selector: 'my-app',
  template: `
    <div [style.background-image]="profileImage" style="width: 961px; height: 688px;"></div>
    <h2> {{message}}</h2>
  `,
})
export class App {

  profileImage: string;
  message: string;

  constructor(private sanitizer: DomSanitizer) {
    this.message = "Before async";
  }

  async ngOnInit() {
    await delay(2000);
    this.message = "Updating Photo";
    const url = 'https://4.bp.blogspot.com/--RBVfn6FzOI/Tq5kOxFGKEI/AAAAAAAACnM/LaiZLD0sUKY/s1600/cats.jpg';
    this.profileImage = this.sanitizer.bypassSecurityTrustStyle(`url(${url})`);
  }
}

Adjustments Made:

1st Modification: Adjusted the constructor from:

constructor(sanitizer: DomSanitizer)

to:

constructor(private sanitizer: DomSanitizer)

This change makes the sanitizer accessible within the class for use in ngOnInit().

2nd Change: Fixed the dimensions of the <div>. By specifying width and height, the size is set manually to prevent automatic adjustment based on the background image size. Different solutions, like maintaining aspect ratio or utilizing an invisible <img>, are detailed in this resource.

3rd Update: Adjusted the image HTTP scheme from http to https to resolve a warning in Plunker related to serving content over https.

View Updated Plunk

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

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

Invoke the built-in matcher within a Playwright custom matcher

I am in the process of implementing a custom matcher for Playwright based on the information provided in the official documentation on extending expect. In a similar vein to this unanswered discussion, my goal is to invoke an existing matcher after modifyi ...

Inverted CSS Shadow Box

I thought I had a good grasp on how CSS shadow-box works, but it seems I was mistaken. Could someone provide me with a visual explanation of why the <hr/> looks the way it does here? Take a look at style 13: https://codepen.io/ibrahimjabbari/pen/ozi ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

Utilizing Angular 2 to Send Emails

How Can I Implement Email Sending Functionality in an Angular 2 App? I have an Angular 2 app hosted on Firebase and I am looking to incorporate a contact form that sends an email. While my preference is to utilize Nodejs for this task, I am open to explor ...

Issues with CSS styling are affecting the display of a form

Hey there! I was working on creating an order form for my website, and everything was going smoothly until I hit a snag while styling the webpage. The problem is that the legends of the form are extending all the way to the right side of the page, and the ...

What are all the different methods I can use to transfer element A to element B, and what are those methods?

While experimenting with Jquery, I encountered a roadblock and now have this question in mind. I wish to enclose all the anchor elements within a newly created div element. <td class="cont-mod-none-options" valign="top" align="right"> <a hr ...

How can grid be used in CSS/HTML to create two collapsible columns that are side-by-side, maintain equal width, and keep their size when expanded?

Hello all, I'm new here and I have a question that I hope I can explain clearly. I am currently working on creating two collapsible "buttons" positioned side by side (each taking up half of the screen width), which expand when clicked to reveal an equ ...

What could be the reason my Angular Bearer Token is not showing up in Firefox?

Here is how my function is structured: testFunctionAuth() { const promise = new Promise((resolve, reject) => { this.http.get(AppConfigService.settings.apiServer.rest + 'systems/all', { headers: { 'Authorization': 'B ...

CSS animations are not running as expected

Currently, I've been experimenting with a basic CSS animation. The objective is to make the application logo move 200px to the right and then smoothly return to its original position. Below is the code snippet I've used for these animations: /* ...

Draggable bar charts in Highcharts allow users to interact with the data by clicking

I'm working on creating a chart that allows for setting values by clicking and dragging. While the dragging functionality is working fine, I've run into an issue with the click event. When I click to set a new value, the draggable feature acts er ...

Tips for maintaining an open ng-multiselect-dropdown at all times

https://www.npmjs.com/package/ng-multiselect-dropdown I have integrated the ng multiselect dropdown in my Angular project and I am facing an issue where I want to keep it always open. I attempted using the defaultOpen option but it closes automatically. ...

Material UI Grid List rows are displaying with an unusually large gap between them, creating a

Currently, I am utilizing Material UI in combination with Reactjs. One particular issue that I am encountering involves the Grid List Component. In my attempt to establish a grid of 1000x1000px, I have specified the height and width within the custom gridL ...

Utilizing Local Files in a Bootstrap Video Carousel

Currently working on a website for a school project and I am trying to incorporate a carousel of videos. After finding a bootstrap carousel template that played videos linked to a server, I attempted to switch it out with local video files without succes ...

compileOnSave has ceased to function

After successfully building my ng4 project with "@angular/material": "^2.0.0-beta.6" and having the compileOnSave feature work fine, I decided to add the following dependencies: "@ngx-translate/core": "^8.0.0", "@ngx-translate/http-loader": "^2.0.0", "an ...

Troubles encountered with fetching pre-filled values in Angular form automation

In my project, there is a template driven angular form for the Edit profile section in the app. Data is populated from the API for the form, with fields being empty if no data is available. When a user types new data into the fields, it is successfully pos ...

Arrange the two buttons in a vertical position

Excuse any weak code you may come across, as I am a backend developer. This is the current appearance of my form: The alignment of these two buttons in Chrome is not correct The issue only occurs in Chrome, with FireFox and Edge displaying the form as e ...

What is the best way to perform unit testing on a function component that includes React.useState() using jest and enzyme?

I'm working on a function component that utilizes React.useState() to handle the state of a drawer modal. My challenge lies in testing this function and its ability to modify state using jest enzyme, as I cannot access its state function due to it not ...

Encountering unexpected compilation errors in an Angular 9 project while utilizing safe null accessing and null coalescing features?

It's really strange what happened with this project. It was working perfectly fine yesterday, and I even left 'ng serve' running after finishing my work without any issues. However, today when I tried to compile the app, I ran into problems ...

Leverage the power of Bootstrap's col-push and col-pull

Here is the code snippet I am currently working with: <div class="col-md-9 col-md-offset-3"> <div class="row> <div class="col-sm-4 col-sm-push-4"></div> <div class="col-sm-8 col-sm-pull-8"></div> </div> ...