问题
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.
回答1:
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.
回答2:
Add the following component in all the components that need background color. The color to be used can be passed in the input attribute:
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
};
}
}
Here is the 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;
}
And the template bg.component.html:
<div class="bg" [ngStyle]="getBgColor()"></div>
Finally in all the components that need background color, add this:
<app-bg [bgColor]="'blue'"></app-bg>
来源:https://stackoverflow.com/questions/48715997/how-can-i-apply-different-full-page-backgrounds-for-different-angular-5-pages