1

i have a list of cards to be displayed in a component. On each card there is a cover-image whose url is coming from server and there is a ngFor in my component.html like this

 <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>

I am getting cover-images in row.companyId.coverUrl. I want to check if row.companyId.coverUrl exist so put the incoming Url but url is not coming form the api so it should put the hardcoded url in background like ./assets/img/abc.jpg

How can i do that?

Fahad Subzwari
  • 2,109
  • 3
  • 24
  • 52

2 Answers2

1

I would try on the subscribe stage:

...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 an URL and wan't to check if the image can be loaded I think you will need a http.get('imageURL').subsribe() then do the test if it responds well.

I highly suggest you take a look at this post too

so this would do something like

in your ts:

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

in your html:

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

not tested

JSmith
  • 4,519
  • 4
  • 29
  • 45
0

Angular pipes exactly fit this scenario.

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')`;
  }
}

and then consume this pipe in HTML

<div [style.background-image]="row | coverImage" class="img-area"></div>
Prabh
  • 989
  • 5
  • 10