javascriptcssangularangular2viewencapsulation

Setting background in Angular2 with encapsulation set as none


I'm trying to set an image to the background of an entire page the following way:

app.component.html

<div [ngStyle]="{'background-image': 'url(' + somePhoto + ')'}">
  <h1>
    Hello, world
  </h1>
</div>

app.component.ts (note: encapsulation set to none)

import { Component, ViewEncapsulation } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
  constructor() { }

  ngOnInit(): void {
    console.log('hello, world');
  }
}

app.component.css

body {
   background-repeat: no-repeat;
   background-size: cover;
   background-position: center center;
   background-attachment: fixed;
 }

The problem is, when using [ngStyle] the image only covers the header portion of the page.

If instead of ngStyle, I select the body directly with something like:

 document.body.style.backgroundImage = 'url(someimage.jpg)';

The image covers the entire page, which is what I want to happen. But I've been told selecting the body directly is bad practice.

How can I get [ngStyle] (or anything else) to create a background image that covers an entire page?

Thanks


Solution

  • You could cover the body with a div of your template, and fill it with the background image, as shown in this stackblitz:

    app.component.html

    <div class="outerDiv" [ngStyle]="{'background-image': 'url(' + somePhoto + ')'}">
        <div>
            <h1>
                Hello, world!
            </h1>
        </div>
    </div>
    

    app.component.css

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

    styles.css:

    html,
    body {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
    }
    

    Note: I added an outer div to allow setting overflow: hidden. Without that style attribute, the default margin of the h1 element prevented the div from filling the top of the body (at least in Chrome on Windows).