【问题标题】:Style for non-ngcontent element非 ngcontent 元素的样式
【发布时间】:2019-01-14 23:37:21
【问题描述】:

Angular 为自己的组件添加不带属性的标签。在 Angular 7 选择器中,/deep/>>>::ng-deep 已被弃用,所以现在我无法通过 :host():host-context() 访问我在化妆中描述的标签。

原妆:

<mat-expansion-panel>
  <mat-expansion-panel-header>expansion-panel-header>
  ...
</mat-expansion-panel>

编译后的化妆:

<mat-expansion-panel _ngcontent-c13="" class="mat-expansion-panel">
  <mat-expansion-panel-header _ngcontent-c13=""></mat-expansion-panel-header>
  <div class="mat-expansion-panel-content">
    <div class="mat-expansion-panel-body">
      ...
    </div>
  </div>
</mat-expansion-panel>

在某些情况下,我在编译我的 SCSS 后得到了什么:

1.
.mat-expansion-panel-body {
  padding: 0;
}

 |
 |
\ /
 V

.mat-expansion-panel-body[_ngcontent-c13] {
  padding: 0;
}



2.
:host-context() .mat-expansion-panel-body {
  padding: 0;
}

 |
 |
\ /
 V

[_nghost-c13]   .mat-expansion-panel-body[_ngcontent-c13] {
  padding: 0;
}



3.
:host() AND :host-context() {
  .mat-expansion-panel-body {
    padding: 0;
  }
}

 |
 |
\ /
 V

[_nghost-c13]   .mat-expansion-panel-body[_ngcontent-c13] {
  padding: 0;
}

但我只想要

.mat-expansion-panel-body[_ngcontent-c13] {
  padding: 0;
}  

请问我该怎么办?

【问题讨论】:

  • 而且,更常见的问题,不止这种情况

标签: angular7 angular-material-7


【解决方案1】:

您通常不能依赖_ngcontent-* 属性,因为它们是动态且不可预测的。这些属性是 Angular 如何“作用域”样式的一部分,以便在一个组件中应用的样式不会影响应用于另一个组件中相同项目的样式。您仍然可以通过将类或属性应用于外部组件来将样式限制在范围内:

HTML

<mat-expansion-panel my-mat-expansion-panel>
  <mat-expansion-panel-header>...</mat-expansion-panel-header>
  ...
</mat-expansion-panel>

CSS

.mat-expansion-panel[my-mat-expansion-panel] .mat-expansion-panel-body {
  padding: 0;
}

出于您的考虑,这与使用 _ngcontent-* 属性(如果可能的话)没有太大区别。

您还可以使用 Angular Material 组件所在的任何组件作为 CSS 选择器的一部分来限制范围:

my-outer-component .mat-expansion-panel .mat-expansion-panel-body {
  padding: 0;
}

请注意,您的样式当然需要在全局样式表中,而不是在组件的样式中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多