1

我有一个父组件parent.html,它的CSS样式如下

.style1{
color:red
}
.style2{
color:red
}

我正在重用这个组件child.html。现在我想覆盖子组件中的父组件样式。我尝试使用::ng-deep它正在工作,但如果 load Parent component,它在父组件中也反映了子组件中的样式覆盖是什么..

我只想覆盖子组件中的样式,但不应该反映在父组件中。我们怎么能做到这一点?

4

2 回答 2

4

为此,您需要encapsulation: ViewEncapsulation.None在父组件中使用,然后您将能够通过添加更具体的选择器(例如在子组件中)来添加覆盖 -

child-component .style1{
   color:red
}

child-component .style2{
   color:red
}
于 2018-10-10T13:26:29.330 回答
0

我认为你必须有两个具有 2 个单独目录的组件,它应该有 html、ts、css 文件。

因此,在父组件的 html 中,您将引用子组件 -
parent.component.html -> <app-child> </app-child>

在子组件中,您应该拥有 - child.component.html、child.component.ts、child.component.css 文件。
如果您在 child.component.css 中创建并添加任何类似的样式,例如 parent.component.css 文件,那么这些样式将被添加到每个组件中,例如p[random_atttr_value],所以现在您将在 child 中为 p 设置单独的样式。

这是角度的默认行为,来自视图封装。由 Angular 之类的影子 DOM 技术使用,并非所有浏览器都支持,但 Angular 就是这样做的。
换句话说,它为浏览器上呈现的每个组件添加了一些属性。
ViewEncapsulation 有 3 个选项 -

encapsulation: ViewEncapsulation.None, 
           ViewEncapsulation.Emulated, (-- this is default)
           ViewEncapsulation.Native (-- only applies to browsers with shadow DOM technology)<br>

希望这将帮助您解决您的问题。

于 2018-10-10T16:18:34.647 回答