我正在尝试使用插值来使用ngFor中的变量为我的元素生成背景图像。
这是我现在所拥有的,完美呈现:
<ion-item-group *ngFor="let game of games">
<ion-card padding style="background: url('./assets/imgs/Body Harvest (USA).png')">
<h2>{{game.name}}</h2>
</ion-card>
</ion-item-group>
游戏对象如下所示:
{
"Id": 30,
"name": "Body Harvest",
"genres": "Action/Adventure/3D shooter",
"date": "30-Sep-98",
"images": "Body Harvest (USA).png",
"developer": "DMA Design",
"publisher": "Midway",
"description": "A video game released for the Nintendo 64.",
"players": 1
},
我正在寻找一种使用以下方式注入URL的方法:
<ion-item-group *ngFor="let game of games">
<ion-card padding style="background: url('./assets/imgs/{{games.images}}')">
<h2>{{game.name}}</h2>
</ion-card>
</ion-item-group>
我认为问题的一部分是'game.images'以双引号返回。
答案 0 :(得分:1)
您可以使用以下
执行此操作<div style="height:200px" [ngStyle]="{background: 'url(https://pbs.twimg.com/profile_images/839721704163155970/'+games+')'}">
Hello
</div>
<强>组件强>
games = "LI_TRk1z_400x400.jpg";
<div [ngStyle]="{background: 'url(/img/' + image + ')'"></div>
答案 1 :(得分:1)
收到数据后,您需要sanitize网址
// component.ts
import { DomSanitizer } from '@angular/platform-browser'
@Component(...)
export class MyComponent {
games;
constructor(private sanitizer: DomSanitizer){}
ngOnInit(){
this.service.getData().subscribe(res => {
res.forEach(item => {
item.backgroundImage = this.sanitizer.bypassSecurityTrustStyle('url("./assets/imgs/' + item.images + '")');
});
});
}
}
// component.html
<ion-item-group *ngFor="let game of games">
<ion-card padding [style.background-image]="game.backgroundImage">
<h2>{{game.name}}</h2>
</ion-card>
</ion-item-group>