Jamil Alisgenderov
Jamil Alisgenderov

Reputation: 1708

Using background-image with ngStyle returns undefined

I try to add images (using API to load items) as background-image of element. But it keeps Cannot read property 'url' of undefined error. Though it actually renders url. Here 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 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;
        }
      });
    }
  }

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

Upvotes: 0

Views: 816

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73721

According to the error message, the photo field is not defined for at least one partner. You can protect against that situation with the elvis operator:

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

or

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

Upvotes: 1

Related Questions