我如何为不同的Angular 5页面应用不同的(完整页面)背景? [英] How can I apply different (full page) backgrounds for different Angular 5 pages?

查看:160
本文介绍了我如何为不同的Angular 5页面应用不同的(完整页面)背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想用背景填充整个屏幕(不只是一个组件),但我想要不同的背景对于每一页,我该如何实现这一目标?



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

  body {
background-color:aqua;

$ / code>

(以背景色为例)

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



我希望你能给我提供的任何帮助,在此先感谢。

解决方案我认为你的问题是,当你添加

  body {
background-color:aqua;
}

添加到您的组件css中,Angular将其重写为

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

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

 从'@ angular / core'导入{Component,Renderer2}; 

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

构造函数(private renderer:Renderer2){
this.renderer.setStyle(document.body,'background-color','yellow');


类似的问题:Angular2将类添加到body标签

角度文档: https://angular.io/api/core/Renderer2

希望这有助于你。

Currently I am using Angular 5 to make an SPA.

I want to fill the entire screen with a background (not just one component) but I want different backgrounds for each page, how can I achieve this?

I have tried this code in the component.css of the concerning page (for example home.component.css):

body {
  background-color: aqua;
}

(using background-color as an example)

Using this method, I thought I could override the main body background per component but it does not seem to work, the page remains empty.

I would appreciate any help you can give me, thanks in advance.

解决方案

I think your issue is that when you add

body {
  background-color: aqua;
}

to your component css, Angular rewrites it to something like

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

You can see it in dev tools if you check. Because of this, the style does not get attached to the body. You can use Renderer2 to change the body style for each component. For example:

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');
  }
}

Similar Question: Angular2 add class to body tag
Angular documentation: https://angular.io/api/core/Renderer2
Hope this helps.

这篇关于我如何为不同的Angular 5页面应用不同的(完整页面)背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆