angular6中如何只为特定组件设置背景图片

How to set the background image only for a particular component in angular 6

我创建了一个名为 login 的新组件,我必须为该组件设置背景图片(login.component.html),仅此而已 component.I 已经尝试了堆栈中提供的许多解决方案 overflow.But图像未设置为 body 的全高。 下面是我的项目文件。

index.html

   <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <base href="/">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/x-icon" href="favicon.ico">
     </head>
     <body>
      <app-root></app-root>
     </body>
   </html>

app.component.html

    <router-outlet></router-outlet>

app.module.ts

   import { BrowserModule } from '@angular/platform-browser';
   import { NgModule } from '@angular/core';
   import { AppComponent } from './app.component';
   import { LoginComponent } from './login/login.component';

   @Component({
     AppComponent,
     LoginComponent
   })
   imports: [
     BrowserModule,
     RouterModule.forRoot([
       { path: '', pathMatch: 'full', redirectTo: 'login' },
       { path: 'login', component: LoginComponent },

           ])

          ],
        providers: [],
        bootstrap: [AppComponent]
             })

       export class AppModule { }

login.component.html

    <div class="inventory-body">
        <!--content goes here-->
    </div>

login.component.css

    .inventory-body {
    margin: 20px 0px;
    color: white;
    padding: 20px;
    height:auto;
    background-image: url('/assets/img/1.jpg');
     }

这是 login.component.ts 文件

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

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

    constructor() { }

    ngOnInit() {

      }

     }
.inventory-body {
 position: fixed; 
  top: 0; 
  left: 0;
  min-width: 100%;
  min-height: 100%;
  background-image: url('')
}

如果要设置高度:auto,必须在 styles.css(全局 css 文件)中将 html、body 和 app-root 高度设置为 100%。对 app.component.css 中的 app.component 和 login.component.css.

中的 login.component 执行相同的操作

Live demo.

全局样式(style.css)

    html, body, app-root {
     height: 100%;
     margin: 0;
     }

在 (login.component.html)

    <body  class="inventory-body">

    </body>

接下来将 css(login.component.css) 写入 (login.component.html)

中的选择器
    .inventory-body {
     position: fixed;
     min-width: 100%;
     background-image: url("/assets/img/img-1.jpg");
     background-repeat: no-repeat;
     background-size: 100%;
     background-position: center;
     background-size: cover;
     }

这对我有用:

 constructor(
    private renderer: Renderer2
  ) {
    this.renderer.setStyle(document.body, 'background-image', 'url(/assets/img/mybackgroundimage.png)');
  }