6

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

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This copies the asset files in the root folder for some reason so they get deployed twice
I almost gave up trying to figure this out. Thank you sir 🫡
-1

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 Comment

however, this is not a perfect solution

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.