使用带有ngStyle的背景图片返回undefined

我尝试添加图片(使用API​​加载项目)为background-image元素。但它保持Cannot read property 'url' of undefined错误。虽然它实际上呈现网址。 这里是模板侧:使用带有ngStyle的背景图片返回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"

回答:

根据该错误消息时,photo字段不为至少一个所定义partner。您可以防止与猫王操作员的情况:

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

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

在控制器

以上是 使用带有ngStyle的背景图片返回undefined 的全部内容, 来源链接: utcz.com/qa/265327.html

回到顶部