使用带有ngStyle的background-image会返回undefined

时间:2017-12-27 13:27:19

标签: javascript angular typescript angular5

我尝试将图片(使用API​​加载项目)添加为元素的 background-image 。但它会导致Cannot read property 'url' of undefined错误。虽然它实际上呈现网址。 这是模板方面:

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

和控制器:

  export class PartnersListComponent implements OnInit {
    partners: {}[] = [];

    constructor(private _partnersService: PartnersService) {}

    ngOnInit() {
      this._partnersService.getPartners().subscribe(data => {
        if (data.status == "200") {
          this.partners = data.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"

1 个答案:

答案 0 :(得分:1)

根据错误消息,未为至少一个photo定义partner字段。您可以使用elvis运营商来防范这种情况:

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

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