2017-07-02 4 views
1

Ich habe eine Reihe von Produkten:Angular Hygienisierung unsichere Art Rohr nicht funktioniert

product_type_one = [ 
{'description': 'Type one sample one', 'type': 'one', 'image': '../assets/1.jpg'}, 
{'description': 'Type one sample two', 'type': 'one', 'image': '../assets/2.jpg'}, 
{'description': 'Type one sample three', 'type': 'one', 'image': '../assets/3.jpg'}, 
] 

ich über dieses Array bin Iterieren mdl-Karten zu erstellen, und ich will jede Karte Produkt einen eigenen Bildhintergrund haben.

Meine Vorlage:

<mdl-card *ngFor="let product of selectedProduct" class="demo-card-event" mdl-shadow="2" style="background-image: url({{product.image}})"> 
    <mdl-card-title mdl-card-expand> 
    <h4> 
    {{product.description}} 
    </h4> 
</mdl-card-title> 
</mdl-card> 

ich nicht so weit Fehler, sondern eine Warnung sagen WARNING: sanitizing unsafe style value background-image: url(../assets/1.jpg)

ich ein Rohr, wie folgend erstellt haben:

import { Pipe, PipeTransform } from '@angular/core'; 
import { DomSanitizer } from '@angular/platform-browser'; 


@Pipe({ 
    name: 'safeHtml' 
}) 
export class SafeHtmlPipe implements PipeTransform { 

    constructor(private sanitizer:DomSanitizer){} 

    transform(html) { 
    return this.sanitizer.bypassSecurityTrustHtml(html); 
    } 

} 

genau Wo kann Ich füge es in meine Vorlage ein, damit Bilder gerendert werden?

Antwort

2

Versuchen Einwickeln gesamte url Anweisung in der bypassSecurityTrustStyle

<mdl-card *ngFor="let product of selectedProduct" class="demo-card-event" mdl-shadow="2" [style.background-image]="product.image | safeHtml"> 
     <mdl-card-title mdl-card-expand> 
     <h4> 
     {{product.description}} 
     </h4> 
    </mdl-card-title> 
    </mdl-card> 

und dann

import { Pipe } from '@angular/core'; 
import { DomSanitizer } from '@angular/platform-browser'; 

@Pipe({name: 'safeHtml'}) 
export class SafeHtml { 
    constructor(private sanitizer:DomSanitizer){} 

    transform(html) { 
    return this.sanitization.bypassSecurityTrustStyle('url(' + html+ ')'); 
    } 
} 
+0

Dies irgendwie keine Wirkung hat, sollte es nicht so etwas wie url sein (...) Wenn ich es in diesem Format ohne safeHtml-Tag schreibe, gibt es nicht einmal eine Warnung, d. H. Style.background-image = "product.image" – Nitish

+0

yeah it soll. oder versuche [style.background-image] = "product.image | safeHtml" – Sajeetharan

+0

und in deiner Pipe this.sanitization.bypassSecurityTrustStyle ('url (' + image + ')'); – Sajeetharan