Is there a way to verify an if-else statement in the ngStyle background property with Angular 7?

I have a collection of cards that need to be shown in a component. Each card contains a cover-image with an URL fetched from the server. In my component.html, I am using ngFor as follows:

<div [style.background-image]="'url('+row.companyId?.coverUrl+')'" class="img-area">
 </div>
 <div class="card-content-area">
  <p class="card-title cursor-pointer" (click)="navigateToCOmpany(row)">{{row.companyId.name}}</p>
 <div class="card-description-area">
    <p class="site-text">{{row.offer_desc}}</p>
 </div>
    <a (click)="referralClick(row, i)" class="site-btn show-desktop-block">Get referral link</a>
    <a (click)="referralClick(row, i)" class="site-link-mobile show-mobile-block"><i class="fa fa-link mobile-link" aria-hidden="true"></i> Get Referral link</a>
 </div>

The cover images are retrieved in row.companyId.coverUrl. If row.companyId.coverUrl does not exist in the API response, I want to use a hardcoded URL like ./assets/img/abc.jpg for the background instead.

How can I achieve this?

Answer №1

For the subscription stage, my suggestion would be:

...subscribe(
  (data:any) => {
    this.row = data;
   if (!this.row){
     this.row = {
       companyId: {
         coverUrl: './assets/img/abc.jpg'
       }
     }
   }
   else if (!this.row.companyId){
     this.row.companyId = {
       coverUrl: './assets/img/abc.jpg'
     }
   }
   else if (!this.row.companyId.coverUrl)
       this.row.companyId.coverUrl = './assets/img/abc.jpg';
  }
)

If you still have a URL and want to check if the image can be loaded, I recommend using http.get('imageURL').subsribe() and then test if it responds successfully.

I also advise checking out this helpful post

So, your code should look something like this:

In your TypeScript file:

localImg = "/assets/img/abc.jpg"

In your HTML file:

[style.background]="'url('+row.companyId?.coverUrl+'), url(' + localImg +')'"

Please note that this code has not been tested

Answer №2

Utilizing Angular pipes in this particular context is a perfect fit.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'coverImage'
})
export class CoverImagePipe implements PipeTransform {
  public transform(row: any): string {
    if (row != null && row.companyId != null) {
      return `url('${row.companyId.coverUrl}')`;
    }
    return `url('./assets/img/abc.jpg')`;
  }
}

After creating the pipe, it can be incorporated in HTML like so:

<div [style.background-image]="row | coverImage" class="img-area"></div>

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

Generating an array of keys from duplicated values in Typescript

My data is structured in the following array format: { itemTitle: 'value example', itemType: 'value example', itemDescription: 'value example', itemFamily: 'Asset', }, { itemTitle: 'val ...

Updating Firebase token in Angular when it has expired

Currently working on a website using Angular, I have integrated the Firebase SDK for email/password authentication. The main aim is to automatically generate a new token if the user closes the site and returns after a week. However, I am unsure which func ...

Handling Concurrent HTTP Requests in Angular using RxJS (Independently Triggered)

Angular 6: Implementing Angular Multiple HTTP Requests with RxJS (for updatePhone and updateAddress) that are independent of each other but may or may not occur simultaneously. Scenario 1: When changes are made to address fields (such as address, state, c ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

Issues arise after upgrading Node and npm, causing an inability to execute any npm command

Following an upgrade to the latest Node and npm version, I encounter an error when attempting any npm command: C:\Users\...>npm doctor TypeError: Cannot read property 'prefix' of undefined at parseField (C:\Users&bs ...

When the URL is entered manually, there appears to be some unusual behavior with Angular

Currently, I am in the process of developing a web application using Angular 7 for the frontend and NodeJS, MongoDB, and ExpressJS for the backend. The app functions as expected when I interact with it by navigating through, but there is an issue when manu ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

Exploring the method to retrieve a dynamically added property in Typescript

My React Component Loader receives certain props. The contentAlign property is only available when the local property exists and its value is 'relative'. I am encountering an error when trying to include contentAlign in the props, and I cannot ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

The child module is unable to locate the route URL for the parent module

I'm new to Angular and I'm working on organizing my code into modules. So far, I have an admin module that responds to the /admin request, but now I want to add a child module called Portfolio Module. Everything is working fine, except for the f ...

Guide to configuring the active Tab in Angular 6 using Angular Material Design

I've searched high and low for a solution to this issue, but I haven't been able to find one. In a particular component, I have a material tab control. However, the active tab doesn't display until I click on one of the tabs on the page. a ...

Can you explain the variances between the two Pick<T,K> util type implementations?

Here is a link I am exploring: https://github.com/type-challenges/type-challenges/blob/master/questions/4-easy-pick/README.md I am struggling to grasp the distinction between these two code snippets: type MyPick<T, K> = T extends {} ? K extends keyo ...

The interaction between Nextjs router and useEffect resulting in unintended re-rendering

I'm currently facing a challenge with Next.js's next/navigation router. In my component, I have a series of useEffects implemented. Strangely, when I call router.replace, one of the effects runs twice or even infinitely in some cases. As a result ...

Enter the newest addition of the node.js layer that bridges the gap between user interface and

Currently, I am in the process of creating a solution on AWS that relies on Cognito for managing users. To kickstart this project, I have referenced the SAAS QuickStart guide available at: SAAS QuickStart However, I am making a significant change by aim ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Attempting to dynamically load an angular2 component upon the clicking of a tab has been my latest endeavor

Currently, I have multiple components loaded on page load within different tabs by using their selectors during design time. However, I am looking to dynamically load those components upon user demand, specifically when a tab is clicked. The issue arises ...

Integrating Angular with Oracle

Exploring the possibility of building applications with Angular/ORDS/Oracle, as I am relatively new to this particular web stack. From what I've gathered so far, it seems like we need a front end, back end, and database in order to create a complete a ...

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

Create generic functions that prioritize overloading with the first generic type that is not included in the parameters

I encountered an issue while utilizing generic overload functions, as demonstrated below in the playground. The generic type T1 is solely used in the return type and not the parameters. Therefore, when attempting to use overload #2, I am required to speci ...

Error encountered while attempting to globally install TypeScript using npm: "npm ERR! code -13"

Issue with npm error 13 Having trouble installing typescript-g package Error details: - errno: -13, - npm ERR! code: 'EACCES', - npm ERR! syscall: 'symlink', - npm ERR! path: '../lib/node_modules/typescript/bin/tsc', ...