Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message

Cannot read property 'url' of undefined
, even though the URL is actually being rendered. Below is the template side:

 <div class="col s12 m4" *ngFor="let partner of partners">
                <div class="card" *ngIf='partner'>
                    <div class="card-image " [ngStyle]="{'background-image': 'url(' + partner?.photo['url'] + ')'}">
                        <a class=" btn-floating halfway-fab waves-effect waves-light blue left ">
                            <i class="material-icons ">shopping_cart</i>
                        </a>
                        <a class="btn-floating halfway-fab red " [routerLink]='"/dashboard/partners/edit/"+partner["id"]'>
                            <i class="large material-icons ">mode_edit</i>
                        </a>
                    </div>
                    <div class="card-content ">
                        <h5 class="center font-weight-400 ">{{partner.name}}</h5>
                        <p class="center ">{{partner.category.name}}</p>
                    </div>
                </div>
  </div>

and the corresponding controller:

  export class PartnersListComponent implements OnInit {
    partners: {}[] = [];

    constructor(private _partnersService: PartnersService) {}

    ngOnInit() {
      this._partnersService.getPartners().subscribe(data => {
        if (data.status == "200") {
          this.partners = data.data;
        }
      });
    }
  }

Here is an example of the data:

category:'',
created_at:"2017-12-27 12:57:50",
deleted_at:null,
first_entry:1,
id:1,
name:"Zara",
photo:{id: 5, url: "example.jpeg"},
updated_at:"2017-12-27 12:57:50",
username:"zara-001"

Answer №1

The error message indicates that the photo field is missing for at least one partner. To handle this issue, you can use the elvis operator as shown below:

[ngStyle]="{'background-image': `url(${partner?.photo?.url})`}"

Alternatively, you can also use:

[style.background-image]="`url(${partner?.photo?.url})`"

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

Exploring the use of arrays in Vue JS

Currently, I am working on a small project using VueJS 2.0, and it involves handling data that looks like this: {"data": [ { "id":8, "salutation":"Mr", "first_name":"Madhu", "last_name":"Kela", ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database. Javascript Function function changeDepartment() { // Initializing and assigning variables va ...

What is the solution to the error message that states a bind message provides 4 parameters, while a prepared statement "" necessitates 5?

Is there a way to fix the issue where the bind message provides 4 parameters but the prepared statement "" requires 5? I've tried solutions from others who faced similar problems without success. (I've included all classes for better error unders ...

What is the process for incorporating an array of models?

let userData = await db.user.findOne({ attributes: attributes, include: ['charges', 'availability', 'practice',// 'services', 'education',// 'user_role', ...

ways to utilize inline styling in react using javascript

When repurposing an array of React components, I am looking to modify the inline styles generated with them. How can I access and log the inline styles of a React component? UPDATE: see the code snippet below: const pieces = this.props.pieces.map((decl, ...

Develop an npm package that includes necessary dependencies

I am working on a distributed node.js project and I want to package the project's domain in a standalone file. To start, I created a package named "common" which contains some utilities by using the following command: npm pack This created the commo ...

What steps can be taken to resolve the error message "How can you repair 'Cannot read properties of undefined (reading 'front_default')'?"

I'm encountering an issue while trying to display data from an API. Although I am able to access the data, a perplexing error keeps popping up that I can't seem to troubleshoot. Here's the error message: Uncaught TypeError: Cannot read pr ...

A Step-by-Step Guide on Modifying the Default Button in Angular2CSV

I am currently utilizing Angular 4 along with the Angular2CSV plugin to transfer data from an Angular page to Microsoft Excel. The process has been successful thus far. However, I am interested in changing the name of the button but am unsure of how to d ...

Struggling to extract specific information from a json array using Angular, my current approach is only retrieving a portion of the required data

My JSON structure is as shown in the image below: https://i.stack.imgur.com/5M6aC.png This is my current approach: createUIListElements(){ xml2js.parseString(this.xml, (err, result) => { console.log(result); this.uiListElement = result[ ...

The error message "MediaMetadata is not defined as no-undef and cannot be used as a constructor" appeared when trying to use MediaMetadata

I have successfully implemented a playlist player using howler.js in vuejs. Now, I am looking to enhance it by integrating the MediaMetadata API. While the MediaSession API is functioning well with controls like notification bar, keyboard controls, and rem ...

Using type values in TypeScript

I am trying to assign interfaces as values within a config object: export interface RouterConfig { startEvents?: typeof RouterEvent[]; completeEvents?: typeof RouterEvent[]; } The intended usage is as follows: private config: RouterConfig = { star ...

Guide to setting up sub-routes in fastify

Currently, I am incorporating fastify as the web framework for my nodejs project. My aim is to organize and call all routes from a specific directory while having a base route established in the main JS file, similar to how it's done in express. Despi ...

Tips for customizing the appearance of ng-bootstrap accordion

Looking to enhance the appearance of ng-bootstrap accordion with some unique fade styling. Any suggestions on how to accomplish this? ...

The TypeScript fs/promises API is experiencing compilation issues when used in JavaScript

While working with TypeScript and the fs/promises API, I encountered an error when compiling and running the TypeScript code. The error message displayed: internal/modules/cjs/loader.js:968 throw err; ^ Error: Cannot find module 'fs/promises' ...

Exploring the Evolution of jsAjaxForm from jQuery Version 2.1.3 to Version 3.2.1

I'm in the process of upgrading to a higher version of jQuery (3.2.1) and encountering difficulties with updating the ajax file upload functionality using jsAjaxForm from jQuery v2.1.3. Is there a similar function that performs the same role as jaAjax ...

The Angular Observable continues to show an array instead of a single string value

The project I am working on is a bit disorganized, so I will try to explain it as simply as possible. For context, the technologies being used include Angular, Spring, and Maven. However, I believe the only relevant part is Angular. My goal is to make a c ...

Subclassing Observable in RxJS 5: Parent class instances are returned by static methods

I've been experimenting with subclassing the RxJS Observable class and overriding the lift method, as explained here. While I can successfully add new operators to the prototype, when trying to create a new Observable using my subclass (such as MyObs ...

Angular HTTP client failing to convert response data to specified type

Recently, I started using the new HttpClient and encountered an issue where the response is not cast with the provided type when making a call. I attempted to use both an interface and a class for casting, but it seems that only interfaces work as shown in ...

Whenever I try to log in on Angular 11, I encounter the HttpErrorResponse error with a status code of

I have encountered an error and cannot seem to find a solution. Here is the code snippet: login(signInRequestPayload: SignInRequestPayload): Observable<boolean> { return this.httpClient.post<SignInResponse>( '/api/v1/registration/login&apo ...