Search code examples
angularng-style

Can't set a background image (with gradient) in Angular 9


As the title states, I can't seem to set this background image. I have tried a number of ways. Currently I have this in my code:

export class HeroComponent implements OnInit {
  @Input() content: PageContent[];

  public backgroundImage: string;

  constructor() { }

  ngOnInit(): void {
    this.getComponent()
  }

  private getComponent(): void {
    this.content.forEach((component: PageContent) => {
      if (component.type !== 'hero') return;
      let url = component.fields.backgroundImage.fields.file.url;
      this.backgroundImage = `linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('${url}');`;
      console.log(component.fields.backgroundImage.fields)
      console.log(this.backgroundImage);
    })
  }
}

The console.log returns this:

linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/default-bg.jpg');

which is right. And my html is trying to do this:

<div class="jumbotron" [ngStyle]="{ 'background-image': backgroundImage }" *ngIf="backgroundImage">

The element is rendered, so there is a background image, but it's not working. Also, I have tried:

<div class="jumbotron" [style.background]="backgroundImage" *ngIf="backgroundImage">

The thing is, if I copy the string and put it in my css like this:

.jumbotron {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/default-bg.jpg');
}

that works without any issues. Does anyone know what I am doing wrong?


Solution

  • I think problem is ; at the end of string. Demo

    this gives result

      backgroundImage="linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/default-bg.jpg')" 
    

    but this doesn't

    backgroundImage="linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/default-bg.jpg');"