gpt4 book ai didi

javascript - 将背景图像与 ngStyle 一起使用会返回未定义

转载 作者:行者123 更新时间:2023-12-03 02:48:31 25 4
gpt4 key购买 nike

我尝试添加图像(使用 API 加载项目)作为元素的背景图像。但它保留了无法读取未定义的属性'url'错误。虽然它实际上渲染了 url。这是模板面:

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

和 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;
}
});
}
}

示例数据:

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字段。您可以使用 elvis 运算符来防止这种情况:

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

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

关于javascript - 将背景图像与 ngStyle 一起使用会返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47993034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com