css - 如何将组件的 [ngClass] 应用于其子元素

标签 css angular angular-components

有没有办法允许在父元素上设置 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] 声明来完成。可以不用中介属性(property)直接做吗?

最佳答案

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

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

ng-deep

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

关于css - 如何将组件的 [ngClass] 应用于其子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59255084/

相关文章:

html - 如何删除由于填充或顶部属性而产生的额外空间

html/css 在中点换行

angular - 在 Ionic 中使用表单会引发错误 : NodeInjector: NOT_FOUND [ControlContainer]

angular - 无法绑定(bind)到 'options',因为它不是 'p-dropdown' 的已知属性

javascript - AngularJS 组件定义为函数

javascript - 标题和侧边栏组件 Angular 6 中的功能共享

html - 为什么跨度会影响兄弟跨度的垂直定位

javascript - 粘性侧边栏不会在页脚之前停止

javascript - 如何向禁用指令添加函数 - Angular 2

Angular - 如何为可选输入属性设置默认值