首页 > 解决方案 > 如何在每个组件的 body 标签中动态加载图像?

问题描述

我是 Angular 的新手,我试图创建这个例子来让我理解。我希望当我从一个组件导航到另一个组件时,我将背景图像动态加载到body标签,我不知道它为什么不加载。

在我包含在该styles部分中的每个组件中,我想为每个组件的主体更改图像。

或者我能做什么?我只想为在我的路由器插座中加载的组件(在我的情况下,mainComponent 和 anotherComponent)中加载不同的背景图像

这是我的代码:

  @Component({
    selector: 'another',
    template: '<a routerLink="/">main</a>',
    styles: [`body {
     position: fixed;
     min-width: 100%;
     background-image: url("https://source.unsplash.com/1920x1080?landscape") !important;
     background-repeat: no-repeat;
     background-size: 100%;
     background-position: center;
     background-size: cover;
    }`]

第二部分:

@Component({
  selector: 'main',
  template: '<a routerLink="/another">anotherComponent</a>',
  styles: [`body {
      position: fixed;
      min-width: 100%;
      background-image: url("https://source.unsplash.com/1920x1080?stars") !important;
      background-repeat: no-repeat;
      background-size: 100%;
    background-position: center;
      background-size: cover;
}`]

这是实时代码:

https://stackblitz.com/edit/angular-9kbx4q

标签: angularangular-componentsangular-template

解决方案


在 Angular 中,您不能从组件样式中覆盖父样式,因为您的组件的样式被封装并且仅适用于您的组件。

您应该在每个组件中添加encapsulation: ViewEncapsulation.None-definition @Componentn({}),您希望在其中覆盖 css 的 body 标记。

这是一个工作示例:

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

@Component({
    selector: 'another',
    template: '<a routerLink="/">main</a>',
    styles: [`body {
    position: fixed;
    min-width: 100%;
    background-image: url("https://source.unsplash.com/1920x1080?landscape") !important;
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center;
    background-size: cover;
    }`],
    encapsulation: ViewEncapsulation.None
})
export class AnotherComponent  {
  constructor(){}
}

重要提示:通过禁用封装,您的组件样式将被全局采用,并将覆盖具有相同类、ID 或标签的样式。

提示:您可以使用此解决方案,但最好将背景图像设置为组件自己的 html 标签。

为您的用例提供更好的解决方案:

将包装器 div 添加到您的anothermain组件模板中。然后将您的样式添加到此包装器 div。像这样:

另一个.component.ts

@Component({
  selector: 'another',
  template: '<div><a routerLink="/">main</a></div>',
  styles: [`div {
    position: fixed;
    min-width: 100%;
    background-image: url("https://source.unsplash.com/1920x1080?landscape") !important;
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center;
    background-size: cover;
  }`]
})

主要组件.ts

@Component({
  selector: 'main',
  template: '<div><a routerLink="/another">anotherComponent</a></div>',
  styles: [`div {
    position: fixed;
    min-width: 100%;
    background-image: url("https://source.unsplash.com/1920x1080?stars") !important;
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center;
    background-size: cover;
  }`]
})

这是关于stackblitz的工作示例。

阅读有关ViewEncapsulation角度文档的更多信息。


推荐阅读