0

Im aware there are similar questions like so.. domSanitizer and WARNING: sanitizing unsafe style value url I have done what has been said in those and I cant seem to get it to work...

app.component.html

<div *ngIf="item?.fields?.asset[0]?.fields?.backgroundImage" class="program-item_background" [style.background]=backgroundImage></div>

app.component.ts

import { DomSanitizer, SafeResourceUrl, SafeUrl, SafeStyle } from '@angular/platform-browser';

export class ProgramItemComponent implements OnInit, OnChanges, Sanitizer {
    @Input() item: Entry<any>; // Program Item getting passed down from the parent        
    backgroundImage: SafeStyle;

constructor(
    private sanitization: DomSanitizer
) { }

ngOnChanges(changes: SimpleChanges) {
    this.backgroundImage = this.safeStyle(this.item.fields.asset[0].fields.backgroundImage.fields.file.url);
}

safeStyle(url){
    return this.sanitization.bypassSecurityTrustStyle(`'url(${url})'`);
}

I'm also getting this error in the console.. enter image description here

but I think thats because it couldnt find the backgroundImage oninit.. due to it being pulled in from an external api

any help would be appreciated! Thanks

EDIT

I have also tried this...

ngOnChanges(changes: SimpleChanges) {
    this.backgroundImage = this.sanitization.bypassSecurityTrustStyle(`'url(${this.item.fields.asset[0].fields.backgroundImage.fields.file.url})'`);
}

but that doesnt seem to working either

Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152

2 Answers2

0

Event though your item has ? in the template, you still have this.item in the class. Which means, you need to make sure this.item always exist. That's why you are getting that error.

windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • this.item does exist (just added it to the question) but because it comes in dynamically when the page first loads its not available but after 2 seconds its avaliable hence why the call is made on `ngOnChanges` – Smokey Dawson Mar 06 '18 at 01:17
0

I figured out a work around instead of using a sanitized url I just used [ngStyle] like so

<div *ngIf="item?.fields?.asset[0]?.fields?.backgroundImage" class="program-item_background" [ngStyle]="{'background': 'url(' + this.item.fields.asset[0].fields.backgroundImage.fields.file.url + ') 50% no-repeat'}"></div>
Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152