5

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 2

10

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.

1
  • This copies the asset files in the root folder for some reason so they get deployed twice
    – Mick
    Mar 19 at 15:00
0

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",
1
  • however, this is not a perfect solution
    – jcdsr
    Jul 30, 2021 at 16:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.