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

``There Seems to be an Issue with Loading Content in Tabs

Hey! I'm encountering an issue with my jquery tabs. The first tab content loads fine, but when I select another tab, the content doesn't display. Then, when I try to go back to the first tab, it doesn't load either. Here's the HTML cod ...

update the value of a specific document in Firestore by specifying its

Is there a way to update document values in a Firestore collection for multiple records without manually specifying each document ID? Currently, I have a method that works for updating individual documents using their IDs, but what if I need to update a la ...

What makes using the `@input` decorator more advantageous compared to the usage of `inputs:[]`

In defining an input on a component, there are two available methods: @Component({ inputs: ['displayEntriesCount'], ... }) export class MyTable implements OnInit { displayEntriesCount: number; Alternatively, it can be done like this ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...

What is the best way to stack an absolutely-positioned element within the children of a sibling element?

I am currently utilizing the vue-slick-carousel package to enhance my website. Within this carousel, there are three key elements that I need to interact with. The first element is an image containing a character identified by the class slide__person. The ...

Develop a precompiled library for Angular applications that utilizes Ahead-of-Time (AOT) compilation technology

My Angular 5 library is packaged for consumption by other apps in their node_modules. Currently, the app is compiled Just-in-Time(JIT) using rollup and gulp. I export it as a package, and developers use it in its JIT compiled form. After researching AOT ...

Encountering an issue with the 'createObjectURL' function in URL, resulting in overload resolution failure when using npm file-saver

While working on my angular app, I encountered a situation where I needed to download user details uploaded as a Word document to my local machine using the angular app. Successfully, I was able to upload and save this data to my database, getting its byte ...

The layout is being disrupted by a bug in the nested list div in IE 7

I am currently in the process of creating a website with nested lists in the sidebar. The parent list contains children li elements. Initially, only 4 list items are displayed, and the rest should be hidden with an option to "Show All" above them. Here is ...

Leveraging Global Variables for Validation in Angular (Angular 10)

I am currently creating a form in Angular 10 which involves the use of validators. Specifically, I have been utilizing the Validators.min() method within my form... Instead of manually inputting the value '100' in the Validators.min('100&ap ...

The implementation of TypeScript 3.5 resulted in a malfunction where the imported namespace was unable to locate the Enum during runtime

I recently upgraded an older Angular.js application from Typescript 2.7 to 3.5 and successfully compiled it using tsc.exe. During application runtime, I encountered an error message in certain parts of the code: TypeError: Cannot read property 'Enu ...

the overflow issue with Summernote's dropdown menu

I am currently working on a 2 columns layout within 2 divs that have different margins set. In the left column, I have integrated a bootstrap datetimepicker and summernote. While the datetimepicker dialog overflows outside the internal div, I am wondering ...

Vue does not recognize the Nuxt $route

Greetings, I've encountered a strange issue. I'm working on a Nuxt app with Typescript. In the created hook, I am using console.log to log this.$route. The log is functioning correctly and I am able to read the params from the route. However, d ...

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

The menu item is having trouble aligning to the right side

Hello, I am currently working on developing a website menu for a project and I am facing an issue with aligning the "Login" Menu item to the right side. Any assistance in resolving this alignment issue would be greatly appreciated. I am also willing to pro ...

Links arranged in semicircles along the perimeter of the page

Here is some code that I have created to display two links in circles positioned on the left and right sides of a webpage. [class*="navigation"] .nav-previous, [class*="navigation"] .nav-next { position: fixed; z-index: 999; top: 50%; text-align ...

PlayWright - Extracting the text from the <dd> element within a <div> container

Here is the structure I am working with: <div class="aClassName"> <dl> <dt>Employee Name</dt> <dd data-testid="employee1">Sam</dd> </dl> </div> I am attempting to retrie ...

Place two divs in the middle of another div with equal spacing in between

I am having trouble aligning two divs horizontally within another div while setting a maximum width for each. Additionally, I would like some spacing between the divs to avoid them touching. The following code isn't yielding the desired outcome: HTM ...

Is it possible for an HTML file to not recognize an external CSS stylesheet?

I've been trying everything, but I can't seem to get these two documents to work together. I'm confident that the CSS file is linked correctly with the right file name. I decided to give it a shot after watching this coding blog tutorial on ...

How to Use CSS to Crop a String from the Middle

My file has a long name and I am using CSS text-overflow: ellipsis to crop it. <style> #fileName { width: 100px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } </style> <div id="fileName"> ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...