如何为Angular组件设置背景图片?

问题描述 投票:0回答:5

在我的角度应用程序中,我想为特定视图设置背景图像。

为此,我将以下内容添加到组件的 css 文件中:

body {
       background-image: url("../../../assets/images/backgroundImage.jpg");
   }

但是,背景没有改变。

这是包含上面显示的 css 代码的文件的文件路径:

角度应用程序/src/app/users/profile/profile.component.css

...这是背景图像的文件路径:

角度应用程序/src/assets/images/backgroundImage.jpg


我也尝试过

body {
       background-image: url("assets/images/backgroundImage.jpg");
   }

...但这导致编译期间出现警告,并且也不起作用。

我做错了什么?


我给了根元素类“root”,然后将以下内容放入CSS文件中:

.root {
   background-image: url("../../../assets/images/backgroundImage.jpg");
}

...现在背景发生变化,但屏幕的整个垂直长度不变(下部保持白色):

css angular url background-image
5个回答
5
投票

根据Angular

@Component
元数据中指定的样式仅适用于该组件的模板内。

你可以使用这样的黑客

在您的

styless.css
文件中添加此

.selector {
       background-image: url("../../../assets/images/backgroundImage.jpg");
   }

现在在你的组件中你可以这样做

ngOnInit() {
    document.body.className = "selector";
  }

ngOnDestroy(){
    document.body.className="";
  }

但是强烈不建议这样做,我不知道你的代码是什么样的,但一定有另一种方法。

  1. 缩放组件以适合整个视口
  2. 设置组件的背景

我将处理一个 plunker 并在完成后链接到此文件作为编辑


1
投票

我将为此添加另一个答案,因为它与我之前的答案完全不同

在您的组件中从

ViewEncapsulation
 导入 
angular/core

import { ..., ViewEncapsulation } from '@angular/core';

在您的 @component 元标记中添加

encapsulation: ViewEncapsulation.None,

@Component({
  ...
  encapsulation: ViewEncapsulation.None,
  ...
})

但这有一个副作用,一旦加载,组件中的所有样式将可供所有其他组件使用。

您可以在Angular页面上查看更多相关信息


0
投票

您可能需要创建一个服务或使用 ngrx 在子组件和 app.component 之间进行通信,以使用 ngClass 切换 app.component.html 的样式。


0
投票

这对我有用,

import { Renderer2 } from '@angular/core';

constructor(private renderer: Renderer2) {
    this.renderer.setStyle(document.body, 'background', 'url("../../../assets/images/form-bg.png")');
    this.renderer.setStyle(document.body, 'background-size', 'cover');
    this.renderer.setStyle(document.body, 'background-repeat', 'no-repeat');
    this.renderer.setStyle(document.body, 'background-attachment', 'fixed');
  }

但是,使用这种方法,可能会出现一些重定向问题。


-1
投票

我的组件中也遇到了同样的问题。我通过将 css 代码放在 styles.css 中解决了这个问题 我给全身贴了标签

.background-IMG {
  background-image: url(../src/app/components/login/images/bg.jpg);
  width: 100%;
  height: 100%;
}
© www.soinside.com 2019 - 2024. All rights reserved.