Search code examples
angulartypescriptng-style

How can i check if else condition in ngstyle background property using angular7?


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?


Solution

  • 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