首页 > 解决方案 > Angular 9中具有特定基本href的css中背景图像的路径

问题描述

angular.json 中的 baseHref 参数是 /iofrog/ + i18n.locales 中定义了 7 种语言,因此 index.html 中的最终 baseHref 是 /iofrog/en 用于英文构建。

在应用程序组件的 css 文件中,我有:

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

这由 Angular 9 CLI 转换为路径 /iofrog/assets/img/background.jpg,因此 /en/ 被跳过!它是 Angular CLI 中的错误吗?

我也试过:

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

我还找到了 --rebaseRootRelativeCssUrls=true|false 选项,但它已被折旧。

有效的解决方法是在 TS 中:

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

在 HTML 模板中:

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

但这并不优雅,并且在呈现 html 后正在加载图像。

Angular 9 中的正确解决方案是什么?

标签: cssangular

解决方案


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.


推荐阅读