【问题标题】:How can I apply different (full page) backgrounds for different Angular 5 pages?如何为不同的 Angular 5 页面应用不同的(整页)背景?
【发布时间】:2018-02-11 01:33:52
【问题描述】:

目前我正在使用 Angular 5 制作 SPA。

我想用一个背景(不仅仅是一个组件)填充整个屏幕,但我想为每个页面设置不同的背景,我该如何实现呢?

我已经在相关页面的 component.css 中尝试过这段代码(例如 home.component.css):

body {
  background-color: aqua;
}

(以背景色为例)

使用这种方法,我以为我可以覆盖每个组件的主体背景,但它似乎不起作用,页面仍然是空的。

如果您能给我任何帮助,我将不胜感激,在此先感谢。

【问题讨论】:

  • 在每个组件的 css 中写下你的 body css background-color 代码,例如你有关于和联系页面,所以关于在 about.component.css 中进行,联系在 contact.component.css 中进行。 ...如果正常的一个不起作用试试这个body{background-color: aqua !important;}
  • 全局样式使用 "styles.css"
  • @RajnishRajput 这对我不起作用。
  • @PrasanthS 这并不是真正的全球性,因为每个页面都有不同的背景。

标签: html css angular single-page-application angular5


【解决方案1】:

我认为你的问题是当你添加时

body {
  background-color: aqua;
}

对于您的组件 css,Angular 将其重写为类似

body[_ngcontent-c0] {
  background-color: yellow;
}

如果您检查,您可以在开发工具中看到它。正因为如此,风格不会附着在身体上。您可以使用 Renderer2 更改每个组件的主体样式。例如:

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

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: [ './home.component.css' ]
})
export class HomeComponent  {
  name = 'Home';

  constructor(private renderer: Renderer2) {
    this.renderer.setStyle(document.body, 'background-color', 'yellow');
  }
}

类似问题:Angular2 add class to body tag
角度文档:https://angular.io/api/core/Renderer2
希望这会有所帮助。

【讨论】:

  • @Mike - 访问浏览器特定的 API,包括窗口、文档和其他 DOM API,在 Angular 中是一种不好的做法。如果你使用 Angular Universal 来获得更好的用户体验和 SEO,那么这种使用文档对象将是一个问题
【解决方案2】:

在所有需要背景色的组件中添加如下组件。可以在输入属性中传入要使用的颜色:

import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core';

@Component({
  selector: 'app-bg',
  templateUrl: './bg.component.html',
  styleUrls: ['./bg.component.scss']
})
export class BgComponent implements OnInit {

  @Input() bgColor = 'red';

  constructor() { }

  ngOnInit() {

  }

  public getBgColor() {
    return {
      'background-color': this.bgColor
    };
  }
}

这是 CSS bg.component.scss:

.bg {
    position: fixed;
    width: 100%;
    height: 100%;
    background-repeat: no-repeat; 
    background-position: center;
    background-attachment: fixed;
    background-size: cover;
    overflow: auto;
}

还有模板bg.component.html:

<div class="bg" [ngStyle]="getBgColor()"></div>

最后在所有需要背景色的组件中,添加这个:

<app-bg [bgColor]="'blue'"></app-bg>

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2019-03-17
    相关资源
    最近更新 更多