0

我在我的组件中使用了一个外部组件。我想在这个外部组件上做一些样式。由于 Angular View Encapsulation,我在组件中定义的所有 css 都不会传播到我的 html 模板中使用的这个外部组件。为了启用这种传播,我设置

encapsulation: ViewEncapsulation.None

这样可行。但是后来我的 css 被应用于我的整个项目,而不仅仅是特定的组件。我需要以某种方式告诉 Angular:“将此 css 应用于此组件及其所有子组件,以及外部组件”。这有可能吗?

4

1 回答 1

1

你可以在你的 CSS 中定义它。但是,要小心,因为 ::ng-deep 是一个非常强大的组合器,如果使用不当可能会导致问题。同样来自 Angular 网站:

不推荐使用穿透阴影的后代组合器,并且正在从主要浏览器和工具中删除支持。因此,我们计划放弃对 Angular 的支持。

CSS:

 :host { color: red; }
 
 :host ::ng-deep parent {
   color:blue;
 }
 :host ::ng-deep child{
   color:orange;
 }
 :host ::ng-deep child.class1 {
   color:yellow;
 }
 :host ::ng-deep child.class2{
   color:pink;
 }

HTML:

  Angular2                                //red
  <parent>                                //blue
      <child></child>                     //orange
      <child class="class1"></child>      //yellow
      <child class="class2"></child>      //pink
  </parent>      
于 2021-10-28T12:12:25.913 回答