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

Trouble loading Styled Components in React Typescript with Webpack configuration

Hey there! I'm diving into the world of styled components for the first time, and I'm a bit lost on where I might have slipped up. I've got my webpack all sorted out and my .babelrc file in place. As I was going through the Styled Component ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Is it true that a TypeScript derived class is not allowed to have identical variable names?

Why is it not allowed for TypeScript derived classes to have the same variable name, even if these members are private? Is there another way to achieve this, or am I making a mistake? class ClassTS { private nom: string = "ClassTS"; ...

Fixing the "Cannot find name" error by targeting ES6 in the tsconfig.json file

I recently started learning AngularJS through a tutorial. The code repository for the tutorial can be accessed at this link. However, upon running npm start using the exact code provided in the tutorial, I encountered the following error: Various TS2304 e ...

Adding properties to React Component

Due to security reasons, I am required to update the ant design library in my codebase from version 3 to 4. In the past, this was how I used the icon: import { Icon } from 'antd'; const Demo = () => ( <div> <Icon type="smile" ...

Angular2 allows for the firing of all columns in one click using *ngFor

<tr *ngFor = 'let student of students> <td contenteditable="true" class ='phone' #button> {{student.phone}} <i (click)='showbox()' class = ' glyphicon glyphicon-edit'></i> <input *ngIf=&apo ...

Incorporating a visual progress indicator on the webpage

I am attempting to create a progress bar in Angular using the angular mat-stepper. Here is the code I have written so far: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { Ap ...

The issue with Angular's Array.push method arises when only the last object in the array is being pushed after a mat-checkbox

I am currently working with two components called item-list and item. The item-list component is responsible for displaying a list of items with checkboxes. I have been facing an issue where the Array that stores the checked items only retains the last ite ...

Transforming an object's type into an array of different types

Looking to create an array of types based on object properties: type T = { a: number | string; b: string | number; c: number; d: boolean; }; Desired Output: [number | string, string | number, number, boolean] Intending to use this as a ...

Could someone shed some light on why my code within the useEffect hook in my component is being triggered twice when it shouldn't be?

I'm currently developing a VR Web project using Three.js within a React-Vite-Typescript setup. As I begin this new project, my focus is on coding the initial view. It starts with a black screen displaying a white logo at the center, reminiscent of in ...

The Angular change detection mechanism is only triggered once when there are consecutive updates to the Ngrx store

I am facing an issue with Angular change detection in a specific scenario while using ngrx-store to manage my application state. Initially, I have state S1. When action A1 is triggered, the state updates to S2 by a reducer. Subsequently, an effect trigge ...

ViewChild with the focus method

This particular component I'm working on has a hidden textarea by default : <div class="action ui-g-2" (click)="toggleEditable()">edit</div> <textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea f ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

Get the jsonarray file using express, node, and angular by downloading it

Within my web application, I am generating jsonarray files. These files have a structure similar to this: [{attr1:"123",attr2:"456"},{attr1:"abc",attr2:"def"}] I need to send these jsonarray files to the client for ...

The header grid will disappear in the p-dialog when the browser is minimized

Check out this informative article on creating a dynamic dialog box using PrimeNG here Take a look at the image below to see how the dialog box appears when opened: One issue I am facing is that the grid header gets hidden when I minimize the browser ...

What are the steps to resolve the MSB4132 error in MSBUILD on a Windows 10 system?

Currently working on an Angular 2 project while using Windows 10. When I ran npm install, I encountered this error message: MSBUILD : error MSB4132 MSBUILD : error MSB4132: The tools version "2.0" is unrecognized. The available tools versions are "12. ...

Unidentified Angular NgRX action

After building my Angular application using NgRX, I integrated actions, reducers, services, and effects. However, when trying to access the action in the component code, I encountered the following error: Error: Property 'GetEmployees' does no ...

Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding? For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09? ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...

Errors occur with Metro bundler while utilizing module-resolver

Recently, I completed a project using the expo typescript template that runs on both iOS and Android platforms, excluding web. To enhance my development process, I established path aliases in the tsconfig.json file as shown below: "paths": { "@models/ ...