有没有办法允许在父元素上设置 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;
}
}
}
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/