【问题标题】:How to apply a component's [ngClass] to its child element如何将组件的 [ngClass] 应用到其子元素
【发布时间】:2022-05-09 19:42:41
【问题描述】:

有没有办法允许在父元素上设置ngClass,但重定向它以便将类实际应用于子元素?

<!-- Parent Component -->
<app-progress-bar [ngClass]="someObject"><!-- Specify [ngClass] here… -->
</app-progress-bar>
<!-- Child Component -->
<div class="progress-bar" [ngClass]="ngClass"><!-- …but it actually applies here -->
  <progress [max]="max" [attr.value]="value">
  </progress>
</div>

显然,这可以通过在父组件上使用自定义 @Input 来完成,然后将该输入输入到子组件中的 [ngClass] 声明中。可以不用中介属性直接做吗?

【问题讨论】:

    标签: css angular angular-components


    【解决方案1】:

    您可以使用::ng-deep 选择器实现此目的。 css 样式将应用于app-progress-bar 组件,但样式将在子组件上激活。

    :host {
      .some-style-evaluated-by-ng-class {
        ::ng-deep .progress-bar {
          background: red;
        }
      }
    }
    

    ng-deep

    不推荐使用穿透阴影的后代组合器,并且正在从主要浏览器和工具中删除支持。因此,我们计划放弃对 Angular 的支持(对 /deep/、>>> 和 ::ng-deep 的所有 3 个)。在此之前 ::ng-deep 应该是首选,以便与工具更广泛地兼容。

    【讨论】:

      猜你喜欢
      • 2014-12-11
      • 2023-03-06
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2019-06-22
      • 2020-01-29
      • 2019-05-29
      • 2019-07-17
      相关资源
      最近更新 更多