What is the process for adding a background image to a div element in Angular 5 once the image has been retrieved from a server-side resource method?

Hey there! Currently, I have an Angular 5 GUI and a Spring Boot application set up. In my Angular component designed for displaying images, I'm facing an issue where the image is not being displayed.

The code snippet from avatar.component.html:

<div class="avatar-circle" [style.background-image]="avatarBgImageStyle" [ngClass]="avatarClasses">
  <fa-icon *ngIf="!user?.avatar" icon="user"></fa-icon>
</div>
<div class="labels" *ngIf="user && (showFullName || showAccount || showAuthority)">
  <div *ngIf="showFullName" class="full-name">{{ fullName }}</div>
  <div *ngIf="showAccount && user.account" class="secondary-text">{{ user.account.name }}</div>
  <div *ngIf="showAuthority && user.authorities && user.authorities.length" class="secondary-text">{{ 'USER_ROLES.' + authority | translate }}</div>
</div>

From the avatar.component.ts file:

import { Component, Input, HostBinding } from '@angular/core';

import { User } from '../../models';
import { getUserFullName } from '../../utils';
import { FilesService } from '../../services';

@Component({
  selector: 'pc-avatar',
  templateUrl: './avatar.component.html',
  styleUrls: ['./avatar.component.scss']
})
export class AvatarComponent {
  // Code here...
}

I appreciate any help. Thank you!

Answer №1

ensure to follow this structure when using a div:

[style.background-image]=" 'url(' +avatarBgImageStyle + ')'"

Answer №2

<div class="user-avatar" [ngStyle]="{ 'background-image': avatarBgImageStyle !== 'none' ? avatarBgImageStyle : ''}" [ngClass]="avatarClasses">
  <fa-icon *ngIf="!userData?.avatar" icon="user"></fa-icon>
</div>

Have you experimented with this method? I'm unsure about how it interacts with asynchronously fetched data, whether it automatically updates when the variable is assigned a value. However, I recommend giving it a shot in this way (unfortunately, I can't test it myself right now).

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

Error: Angular is unable to process the subscribe property because it is undefined

I keep encountering a peculiar error that reads "cannot read subscribe of undefined". Interestingly, this error only seems to occur sporadically when the code is run on its own, but almost always arises during testing without focus. I'm at a loss as t ...

Error: The current call does not match any existing overloads - TypeScript, NextJS, styled-components

I'm facing an issue while trying to display icons in the footer of my website. The error message "Type error: No overload matches this call" keeps appearing next to my StyledIconsWrapper component, causing Vercel deployment to fail. Despite this error ...

Having trouble with sending values to Angular 7 components' HTML pages

Struggling with a simple task and encountering an error: Code snippet below: app.component.html <div class="col-md-{{myvalue}}">stuff here</div> app.component.ts myvalue: string; ngOnInit() { this.myvalue('6'); } Seeing th ...

Tips for positioning a mat-form-field beside an h1 tag

I've been attempting to place an h1 next to a mat-form-field from Angular Material, but I'm encountering some difficulties. Here's what I've attempted so far: <div class="mat-elevation-z8"> <mat-form-field> <mat-l ...

Testing Angular 16 Component with Jasmine Spy and callFake Strategy

I've encountered an issue while trying to test my component unit. The problem arises when I call the product-list.component.ts from my product.service.ts. While my product.service.spec.ts is successful, the product-list.component.spec.ts fails as the ...

The module named 'RatingModule' does not seem to be a valid NgModule class

I am currently encountering an issue with using the starrating module in Angular 13. After installing the package, I consistently receive the following error message whenever I attempt to call the module in my AppModule: 'RatingModule' does not s ...

The TypeScript error message "Type 'x' cannot be assigned to type 'IntrinsicAttributes & IntrinsicClassAttributes<Class>'" was displayed on the screen

I encountered an issue when trying to pass a class method to a child component in a new code. While it worked perfectly in another code, I am now receiving the following error message: view image here What steps should I take to resolve this error? Do I ...

Issues with getOptionLabel in Material UI

I have a constant with the following values : const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ]; and my Autoco ...

Avoid unintentional type conversions from Number to Array in Typescript

What is the best way to avoid implicit casting from a number to an array? @Component export default class FeedbackMain extends Vue { currentState : Number = 0; mounted () { this.currentState = "Hello" // Type '"Hello"' is not assignable to ty ...

Using Primeng to implement pagination and lazy loading in a dataView

Looking for a way to search through product data with filters and display it using primeng dataview? Consider implementing pagination in your API that pulls products from the database page by page. Set the products array as the value in dataview so that wh ...

Running NG BUILD from Gulp can be done using either child-process.spawn or by disabling all output in child-process.exec

Have you come across a similar question like this Call "ng build" from inside a gulp task? I have found a way to successfully build Angular using Gulp in order to prevent overflowing the output buffer. Here's how I achieved it: const child ...

The animation feature of the CountTo Module fails to function properly once the currency pipe is included

My end goal is to achieve a final view that looks like this: https://i.sstatic.net/VUGdb.png The values are supposed to have a counter animation from 0 to the specified final value. I have also implemented a currency pipeline in the value section for sep ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

Pressing the enter key triggers a peculiar activation sequence for FormArray with add/remove buttons

In my interactive form, I have implemented functionality to add and remove a list of items using FormArray. Each item in the list has a Remove button associated with it for deletion. Additionally, there is an Add button that allows users to include new ite ...

Just a straightforward Minimum Working Example, encountering a TypeScript error TS2322 that states the object is not compatible with the type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

Currently, I am immersed in a project involving React and Typescript. I am grappling with error code TS2322 and attempting to resolve it. Error: Type '{ submissionsArray: SubmissionProps[]; }' is not assignable to type 'IntrinsicAttributes ...

Tips for modifying an observable

Previously, I utilized Firebase as my database service. When I received the Observable from Firebase and subscribed to it: const projectsFromDatabase = this.afDB.list(this.basePath, { query: query }); console.log(projectsFromDatabase.subscribe(res =&g ...

Reusing Ionic headers across multiple pages

I'm looking to reuse my HTML header across different pages within an Ionic 4 app. Here is a snippet of my code: header.html <ion-view> <ion-grid> <ion-row> <ion-col col-6 class="font"> < ...

Tips for setting up a responsive dropdown field in an Angular 6 reactive form for an Edit page

When creating a drop down field with API values, I encountered an issue where all data was displayed on the edit page instead of just the previously stored value. The drop down field showed all options instead of the selected one. Below is the code for the ...

Sending Angular signal from child component to parent component

While working in Angular, I have been utilizing event emitters to transmit data from a child component to a parent component. This allows the parent component to update shared data based on notifications from the child. Now with Signal being introduced i ...

Error message: Object literal is limited to declaring existing properties

The source code was obtained from this Codesandbox demo: CodeSandbox - Cover Image Example Subsequently, an .eslintrc configuration file was generated with the following content (the only content present): { "extends": "react-app" } However, a TypeScri ...