path to background-image in css with specific base href in Angular 9

Viewed 3419

The baseHref param in angular.json is /iofrog/ + there are 7 languages defined in i18n.locales, so the final baseHref in index.html is /iofrog/en for English build.

in css file for app component I have:

background-image: url('~/assets/img/background.jpg'); 

This is translated by Angular 9 CLI to path /iofrog/assets/img/background.jpg, so /en/ is skipped! Is it a bug in Angular CLI?

I also tried:

background-image: url('/assets/img/background.jpg');  // not showing the image
background-image: url('./assets/img/background.jpg'); // compiler error
background-image: url('assets/img/background.jpg');  // not showing the image

I also found --rebaseRootRelativeCssUrls=true|false option but it is depreciated.

The workaround that is working is in TS:

this.backgroundImageURL = `url(${this.baseHref}assets/img/background.jpg)`;

And in HTML template:

[style.background-image]="backgroundImageURL ? backgroundImageURL : ''"

But this is not elegant and the image is loading after the html is rendered.

What is the correct solution in Angular 9?

2 Answers

There were some issues with i18n building angular app and base href.

It should work with that syntax for scss files:

background-image: url('~src/assets/img/background.jpg');

Hope this helps.

Works for me in package.json add this to your command

--base-href ../ --deploy-url ../

or

--base-href ' ' --deploy-url ' '

CSS if loads an asset:

background-image: url('/assets/graphics/image.svg')

on index.html 1st line as <base href="/">

Double-check in angular.json - "projects"

  "root": "",
  "sourceRoot": "src",
  "projectType": "application",
  "prefix": "app",
Related