2017-12-09 7 views
0

ngForからの変数を使用して要素の背景画像を生成するために補間を使用しようとしています。ここで角度補間を使用して動的URLを要素スタイルに挿入するにはどうすればよいですか?

が完全にレンダリングされ、私が現在持っているものです。

<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」が二重引用符で囲まれていることが問題の一部だと思います。

答えて

1

あなたがあなたのデータを受信した後、あなたがsanitizeへのURLが必要になります

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

を使用してこれを行うことができますWorking Example

関連する問題