2017-12-09 14 views
0

ngFor의 변수를 사용하여 내 요소의 배경 이미지를 생성하는 데 보간을 사용하려고합니다.각도 보간을 사용하여 동적 URL을 요소 스타일에 삽입하려면 어떻게해야합니까?

{ 
    "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/Body Harvest (USA).png')"> 
    <h2>{{game.name}}</h2> 
    </ion-card> 
    </ion-item-group> 

게임의 목적은 다음과 같습니다 : 여기

내가 현재 가지고 완벽하게 렌더링하는 무엇

<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