【问题标题】:How can I apply different (full page) backgrounds for some specific URL in angular?如何以角度为某些特定 URL 应用不同的(整页)背景?
【发布时间】:2019-03-17 19:10:59
【问题描述】:

我想将不同的整页背景颜色应用到我的登录页面,并将“登录”作为 URL。我在登录组件中使用 ngAfterViewInit() 和 Renderer2。当我访问此页面并返回其他页面时,我的页面的所有背景都像我的登录页面一样改变,但我只想改变我的登录页面背景颜色。

我的登录组件使用 Renderer2

import {AfterViewInit, Component, ElementRef, OnInit, Renderer2} from '@angular/core';
import {Router} from '@angular/router';

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

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

  ngOnInit() {
  }
}

我的登录组件使用 AfterViewInit

从 '@angular/core' 导入 {AfterViewInit, Component, ElementRef, OnInit, Renderer2}; 从'@angular/router'导入{Router};

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

  constructor(private elementRef: ElementRef, private router: Router) {
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
this.elementRef.nativeElement.ownerDocument.body.style.backgroundColor = '#E7fff4';
    }
}

【问题讨论】:

  • Angular 应该有一个 ng-class 的等价物
  • 将 bool var 设置为 this.router.url === '/login' 并在父元素上放置类似 [ngClass]="{'special-background-class': isLoginUrl}` 的内容并应用该类。
  • 这里有一个问题,我想要整页,即使我们有滚动页面也必须有这个背景颜色,所以就像我们在标题标签的正文上设置它一样,我不能将它应用到我的登录.component.html 文件导致当我们滚动页面时它无法正常工作整页高度。

标签: javascript angular typescript


【解决方案1】:

请进行以下更改:

ngOnInit() {
  this.renderer.setStyle(document.body, 'background-color', 'yellow');
}

ngOnDestroy() {
  this.renderer.removeStyle(document.body, 'background-color');
  // or whatever color you want to change when user move out of login page
}

【讨论】:

    【解决方案2】:

    一种方法是使用共享函数使用 AfterViewInit 和 OnDestroy 切换主体类...

    export class LoginComponent implements AfterViewInit, OnDestroy {
    
      toggleBackgroundClass(): void {
        document.querySelector('body').classList.toggle('your-class-name');
      }
    
      ngAfterViewInit(): void {
        this.toggleBackgroundClass();
      }
    
      ngOnDestroy(): void {
        this.toggleBackgroundClass();
      }
    
    }
    

    当你的组件加载时,它会设置背景类,当你离开时,它会移除这个类。你的 CSS 可以很简单:

    body.your-class-name {
      background-color: #E7fff4;
    }
    

    【讨论】:

      【解决方案3】:

      移除渲染器和元素引用

      要将其限制在一个组件中,请将其添加到 scss

      :host{
         backgroundColor = '#E7fff4';
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 1970-01-01
        • 2022-11-26
        • 1970-01-01
        • 2019-01-01
        • 1970-01-01
        • 2017-10-16
        相关资源
        最近更新 更多