'How to apply a component's [ngClass] to its child element
Is there a way to allow ngClass
to be set on a parent element, but redirect it so the classes are actually applied to a child element?
<!-- 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>
Obviously this could be done by using a custom @Input
on the parent component, then feeding that input into the [ngClass]
declaration in the child. Can it be done directly without an intermediary property?
Solution 1:[1]
You could achieve this with the ::ng-deep
selector. The css styles will be applied on the app-progress-bar
component but the styles will be activated on the child.
: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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | C_Ogoo |