Angular background image not displayed

After searching extensively, I came across many examples that didn't work for me. I'm not sure what I'm doing wrong and I need assistance!

I noticed that I can see the image if I use the <img> tag, but not when I try to set it as a background-image. However, I can view the binary image when inspecting the element.

As an attempt to solve the issue, I created an example in StackBlitz: Example on StackBlitz

Here is the HTML:

 <!-- This works -->
 <div class="row" style="max-width: 100%; margin-left: 1px;" >
     <img id="dashboardImage" [src]='imageBlobDataUrl' height='500' width='500' />
 </div>

 <!-- This does NOT work -->
<div class="row" style="max-width: 100%; margin-left: 1px;" [style.background-image]="image"> </div>

And here is the TypeScript code:

    @Input() imageBlobDataUrl: any;
    selectedImage: QiImage = new QiImage();

    public header:SafeHtml;
    public content:SafeHtml[];
    public image:SafeStyle;

  constructor(
          private qiImageService: QiImageService,
          private sanitizer: DomSanitizer,
          private imageService: ImageService
  ) {}
  populateImageDetails(lineId, bitmapFileName) {
      this.imageService
          .populateImageDetails(lineId, bitmapFileName)
              .subscribe( (selectedImage : any) => {
                  this.selectedImage = selectedImage;
                  //let TYPED_ARRAY = new Uint8Array(selectedImage.imageData);
                  //const STRING_CHAR = String.fromCharCode.apply(null, TYPED_ARRAY);
                  //let base64String = btoa(STRING_CHAR);
                  let objectURL = 'data:image/png;base64,' + selectedImage.imageData;
                  this.imageBlobDataUrl = this.sanitizer.bypassSecurityTrustUrl(objectURL);
                  this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${objectURL})`);
              });
  }

https://i.stack.imgur.com/fR3tJ.png

Answer №1

After testing your code on the stackblitz platform, I found that it functions properly. However, you just need to make some adjustments to the CSS in order to display the image correctly.

Avoid using bypassSecurityTrustUrl when dealing with Style Urls. Here's an example of what not to do:

this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL); // Avoid this method

this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${objectURL})`); // Use this approach instead

Make sure to tweak the CSS positioning for your image to ensure it appears as intended:

<div class="row" 
  style="width: 100%; height: 100%; position:absolute; 
  margin-left: 1px;  background-repeat: no-repeat;" 
  [style.background-image]="image"> </div>

Answer №2

Have you ever attempted to change the background image using CSS? Perhaps something like this:

.bg {
  background-image: url("../../yourimage");
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;

}

You can utilize data binding in the template to customize the CSS class as desired.

Answer №3

It's easy to display an image from a URL even if it's encoded in base64 format.

<img id="dashboardImage" [src]='objectURL' height='500' width='500' />

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

Applying personalized CSS to an element based on the condition of a child element in the previous sibling element

I am trying to apply styles to a span element only when a child element in a preceding sibling div element is active, which means a radio button has been checked. I am unable to modify the code and can only use CSS for this task. Any ideas on how to achi ...

Steps for generating a multer file using a link to an image

My current challenge involves downloading an image from a public URL, converting it into a multer file format, and then uploading it using an existing API. So far, I've experimented with axios using responseType: "blob" and responseType: "arraybuffer" ...

Is it feasible to restrict a generic type using typeguard?

I'm currently working on refining a generic function, where the autocomplete feature recognizes that it's encountering a typeguard, preventing it from revisiting the same code block. I suspect that the issue lies in not restricting the type to th ...

What could be causing transition to not be recognized as an element in HTML?

<template> <header> <nav class="container"> <div class="branding"> <router-link class="header" :to="{name : 'Home'}">>FireBlogs</router-link> </div& ...

The issue with responsive design not functioning properly on the iPhone

This is my first attempt at creating a responsive design, but it's not turning out as smooth as I expected! I have set up breakpoints at 768 and 480, and the design breaks correctly when I resize the browser. However, when I tested it on my smartphon ...

Every key must be a string or number; received a function instead

I encountered a peculiar situation while working with Cucumber: Scenario Outline: Protractor and Cucumber Test InValid Given I have already...... When I fill the <number> .... Examples: | number|... | 3 |... |4 |... Moreover, I ...

Contrasting input: [] with the @Input() directive

Recently, I've begun exploring the world of child and parent component communication in Angular 4. In my research, I stumbled upon older videos that utilize the input: [] syntax instead of the now more prevalent @Input() syntax. Is there any distincti ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

Tips for adjusting the font size on the Google Maps mapType controller

Is it possible to adjust the font size of a Google Maps mapType controller using HTML or CSS? I've managed to change the size of the controller, but struggling with the font size. HTML: <div #map id="map" style="height:250px;"></div> C ...

Experiencing difficulty creating query files for the apollo-graphql client

I'm currently attempting to learn from the Apollo GraphQL tutorial but I've hit a roadblock while trying to set up the Apollo Client. Upon executing npm run codegen, which resolves to apollo client:codegen --target typescript --watch, I encounter ...

Tips for generating a list in Angular2 based on previous selections

import { Component } from '@angular/core'; export class Superhero { name: string; } const SUPERHEROES: Superhero[] = [ { name: 'GK-1' }, { name: 'GK-2' }, { name: 'GK-3' }, { name: 'GK-4&ap ...

Customizing Row Background Color in Bootstrap

Currently working on a project www.codepen.io/anon/pen/yMmjZb The problem I am facing is with my 3rd row (the one with the 3 columns) where the background color is bleeding beyond the intended boundary. My suspicion is that it's due to the row span ...

Changing direction of arrow upon dropdown menu opening with JavaScript

I have developed a piece of code that enables users to click on a div in order to reveal a dropdown menu containing radio buttons. My goal is to make the arrows rotate 180 degrees when the dropdown menus are opened, and then return to their original positi ...

The concept of CSS Parent Elements refers to the relationship

Is it possible to dynamically apply CSS style based on the parent property of a div element using JavaScript? Here is an example: <div clas="parent"> <div class="child"> <div class="x"></div> </div> </d ...

Is there a way for me to loop through an object without prior knowledge of its keys?

Upon receiving data from the server, it looks something like this: { "2021-10-13": { "1. open": "141.2350", "2. high": "141.4000", "3. low": "139.2000", "4. close& ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

Utilize CSS to eliminate gaps between spans

I can't figure out how to remove the vertical spacing between these two spans. Any help would be greatly appreciated. The issue I'm facing is the large gap between these two spans: <span class="twentyeight nomargin threshold_green">6</ ...

Error encountered: The term 'interface' is a restricted keyword

I am in the process of developing a NodeJS and MongoDB library for performing CRUD operations on APIs. My goal is to establish an interface with Typescript that includes the url and database name, structured as follows: However, I am encountering this par ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...