0

I am trying to set the background image using ngStyle,

<div  class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image':  'url(../imgs/banner/' + event?.category + '.jpg)'  }">

it works when the category is one word, but it does not work when it has two words, it binds as null

for example when it comes as "Formula one" it binds as null. what is the issue?

1 Answer 1

1

URL with spaces will not get interpreted directly, Try this,

<div class="artist-banner fluid-banner-wrapper" [ngStyle]="alertStyles">

In component,

alertStyles = {
        'background-image':  'url(../imgs/banner/' + this.event?.category.replace(" ", "%20") + '.jpg)'
      };

Example:

@Component({
  selector: 'app-style-example',
  template: `
    <div  class="artist-banner fluid-banner-wrapper" [ngStyle]="alertStyles">
  `
})
export class StyleExampleComponent {

  alertStyles = {
    'background-image':  'url(../imgs/banner/' + this.event?.category.replace(" ", "%20") + '.jpg)'
  };
}

Edit: If yor are looping the event, you should pass event parameter

   @Component({
      selector: 'app-style-example',
      template: `
        <div  class="artist-banner fluid-banner-wrapper" [ngStyle]="changeStyle(event)">
      `
    })
    export class StyleExampleComponent {


    }



  changeStyle(event) {
    return {
        'background-image':  'url(../imgs/banner/' + event?.category.replace(" ", "%20") + '.jpg)'
    }
  }
Sign up to request clarification or add additional context in comments.

6 Comments

this is angular2
you tagged angular
angular is angular2
was this in a loop?
according to your sample where is the event coming from? your answering is totally deviating
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.