Use dynamic css background image with url


#1

Hello,
I am trying to do something that look easy but I can’t find a solution for now…
I need to change dynamically a component (Stacklayout) background image and I wrote this code:

    <StackLayout style="background-image: url('{{ this.backgroundImage != undefined ? this.backgroundImage : '' }}');">
    </StackLayout>

but I have an error if this.backgroundImage is undefined because url(“”) throw an error.
I have tried to use

    <StackLayout [style.background-image] = "backgroundImage" >
    </StackLayout>

but I need to have an image, not a string in this.backgroundImage. I pure Angular we can use :


this.backgroundImage = this.sanitizer.bypassSecurityTrustStyle(`url(${page.backgroundImage.path})`);

but in Nativescript there is no DOM sanitizer and I don’t know how to solve this.

Anyone has an idea??

Thanks!
Serge


#2

What if you do somethink like this?

<StackLayout [style.background-image]="backgroundImage ? 'url("' + backgroundImage + '")' : null" >
 </StackLayout>

But I think it would be cleaner, if you did the string concatenation in JS/TS instead of in the template.

Something like this:

get backgroundImageUrl() {
   if (this.backgroundImage) {
     return `url("${this.backgroundImage}")`;
  }

  return null
}

#3

Thanks, works fine with backgroundImageUrl() !