【问题标题】:Pierce component style globally全局穿透组件样式
【发布时间】:2019-10-27 13:24:54
【问题描述】:

我需要从全局 styles.scss 文件中穿透我的组件的样式。

基本上,我使用了包裹在custom-component 中的mat-card 组件。在 在某些情况下,当自定义组件前面有另一个 custom-component

时,我想将样式更改为 mat-card

这个想法是:

全局样式.scss

custom-component ~ custom-component::ng-deep { 
    .mat-card {
       background-color: red;
    }
}

host-context 似乎是个好主意,我试过这样

自定义组件.scss

// does not work
host-context(~custom-component) { background-color: red; }

我已经尝试过这个和其他一些组合,但它们似乎不起作用。我们应该如何使用 >、~、+ 选择器来设置角度组件的样式?

干杯

【问题讨论】:

    标签: css angular sass angular7 angular-material2


    【解决方案1】:

    我个人不惜一切代价避免刺穿选择器。它破坏了整个组件模型,并紧密耦合了代码。

    我会以稍微不同的方式处理这个问题。我会让我的custom-component 有一个可选的Input() embedded = false

    你的用法可能如下:

    // top level
    <custom-component></custom-component>
    
    // nested level
    <custom-component [embedded]="true"></custom-component>
    

    然后使用ngClassembedded 属性来触发颜色变化。

    有关ngClass 的更多信息,请参阅文档 https://angular.io/api/common/NgClass

    【讨论】:

    • 在此处查看示例:stackblitz.com/edit/…
    • 这是一个很好的方法,但不是我想要的。我知道我们不应该使用穿孔,但在这种情况下,我想根据“~”选择器来设置组件的样式。
    【解决方案2】:

    好吧,这不是一个解决方案,但需要考虑一件事。

    如果您想使用选择器your-component 将样式应用于组件,则必须在组件:host 中设置display: block; 属性。我完全错过了这个,但它看起来像这样:

    你的组件.css

    :host {
      display: block;
    }
    

    你的父组件 css

    your-component ~ your-component {
      margin-top: 15px;
    }
    

    而且它有效。我的问题最初与此有关。

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2019-11-09
      • 1970-01-01
      • 2020-09-06
      • 2021-03-06
      相关资源
      最近更新 更多