简体   繁体   English

使用View封装时Angular不会封装CSS

[英]Angular does not encapsulate css when using View encapsulation

I Have two menus in my app. 我的应用程序中有两个菜单。

Both of them are using primeng Panel Menu 他们两个都使用primeng 面板菜单

I have changed their css. 我改变了他们的CSS。

The problem is now after adding the second-menu to my app, left-menu 's style has changed. 现在的问题是,将second-menu添加到我的应用程序后, left-menu的样式已更改。

I tried to use View encapsulation on both of them, the left-menu style still not encapsulated 我试图对它们两个都使用View encapsulationleft-menu样式仍然没有封装

Here's the first menu header 这是第一个菜单标题

@Component({
  selector: 'app-left-menu',
  templateUrl: './left-menu.component.html',
  styleUrls: ['./left-menu.component.css'],
  encapsulation: ViewEncapsulation.Emulated

})

Second menu 第二菜单

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

In my CSS I use ng-deep and :host 在我的CSS中,我使用ng-deep:host

here's an example 这是一个例子

:host ::ng-deep .ui-panelmenu-header.ui-state-default:hover {
  background-color: #555555;

} 

Here's a stackblitz example 这是一个stackblitz的例子

I won't add all the CSS because it's the same on both styles 我不会添加所有CSS,因为两种样式都相同

Using only ::ng-deep will affect all the classes in the project even if not children of the component where the css is declared. 仅使用::ng-deep将影响项目中的所有类,即使不是声明css的组件的子代也是如此。 ( here is a simple stackblitz reproduting this behavior ) 这是重新生成此行为的简单stackblitz

If you want to affect only child elements of the component but not the elements on the same level, you should use :host with the ::ng-deep . 如果只想影响组件的子元素,而不影响同一级别的元素,则应将:host::ng-deep

Here is a fork of your stackblitz with a fix suggestion. 这是您的堆叠闪电战中的一个分支,带有修复建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM