首页 > 解决方案 > Angular 2+:组件样式不断影响其他组件

问题描述

将home 组件background-color:red写入其 scss,然后将用户组件background-color:green写入其 scss。我启动我的应用程序,我在家,背景为红色,进入用户页面,背景为绿色。像它应该的那样工作......但是现在当我回去时,我的家庭组件背景仍然是绿色的。所有组件都有ViewEncapsulation.None. 如果我从用户页面开始导航,会发生同样的事情,但背景颜色 vica-vera。

我一直明白组件样式的重点是仅影响其组件而不影响其他组件。这不是应该如何工作的吗?

编辑:如果我设置ViewEncapsulation.Emulated,我看不到组件样式 scss 文件的样式正在应用,因此两个页面都有白色背景。这是我的主组件文件的外观:

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


@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss'],
    encapsulation: ViewEncapsulation.Emulated,
})

export class HomeComponent implements OnInit {

    ngOnInit() {

    }

}

编辑:您看到我的问题是我为 设置背景颜色<body>,但正文不是模板的一部分,这就是为什么encapsulation: ViewEncapsulation.Emulated组件样式表不会影响它。

标签: angular

解决方案


您需要将视图封装到Emulated,以便您的组件装饰器如下所示 -

@Component({
    // ...
    encapsulation: ViewEncapsulation.Emulated,
})

它只会将您的样式限定为特定组件。

这里有更多关于视图封装的参考


推荐阅读