Search code examples
angulartypescriptng-style

Binding variable binds as null when bind using ngStyle


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?


Solution

  • 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)'
        }
      }