Angular 2+:组件样式不断影响其他组件 [英] Angular 2+ : Component style keeps affecting other components
问题描述
将具有 background-color:red
的家庭组件写入其scss,然后将具有 background-color:green
的用户组件写入其scss.我启动我的应用程序,我在家里,有红色背景,转到用户页面,有绿色背景.像它应该的那样工作...但是现在当我回去时,我的家庭组件背景仍然是绿色的.所有组件都具有 ViewEncapsulation.None
.如果我从用户页面开始导航,也会发生相同的情况,但是背景颜色为vica-vera.
Got home component with background-color:red
written into its scss and then got user component with background-color:green
written into its scss. I start my app, I am at home, got red background, go to user page, got green background. Works like it should...but now when I go back my home component background is still green. All components have ViewEncapsulation.None
.
If I start navigation from user page, same things happen, but background colors vica-vera.
我一直都知道,组件样式的要点是仅影响其组件而不影响其他组件.这不是应该如何工作的吗?
I always understood that point of component style is to affect only its component and not others. Is it not how that supposed to work?
如果我设置了 ViewEncapsulation.Emulated
,则我看到的组件样式scss文件没有样式,因此两个页面都有白色背景.这是我的家庭组件文件的外观:
If I set ViewEncapsulation.Emulated
I see no styling from component style scss file being applied, so both pages are having white background.
This is how my home component file looks:
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>
设置背景颜色,但是模板的body aint部分,这就是为什么 encapsulation:ViewEncapsulation.Emulated
和组件样式表不会影响它.
You see my problem was that I was setting background color for <body>
, but the body aint part of the template, this why encapsulation: ViewEncapsulation.Emulated
and component stylesheets aint affecting it.
推荐答案
您需要将视图封装为 Emulated
,以便您的组件装饰器如下所示-
You need to encapsulate your view to Emulated
, so that your component decorator will look like the following -
@Component({
// ...
encapsulation: ViewEncapsulation.Emulated,
})
它将仅将样式限制为特定的组件.
此处 有关视图封装的更多参考
Here's more reference about View Encapsulation
这篇关于Angular 2+:组件样式不断影响其他组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!