Reputation: 729
I have a component that has encapsulation: ViewEncapsulation.None
. I have defined a css class;
a.component.css:
.icon{
font-size: larger;
&::before{
color: steelblue;
}
}
Other definitions made in a.component.css needs to be applied application-wide so ViewEncapsulation.None
configuration is needed and used. But I have .icon class that needs to be applied only in the a.component. And it's used so frequently in the component, so adding a new class or changing the class name doesn't seem to be best practice.
Are there any ways to apply a specific css class only to the component which uses ViewEncapsulation.None
?
ps: I have tried to use :host
selector but didn't work.
Upvotes: 1
Views: 642
Reputation: 1508
The :host
only works for components that have the encapsulation on.
If you take a look at the Angular Material source code, you can see how they tackle that problem, because all of their components have encapsulation off. They basically add a class name to every component and use the class selector to create their own encapsulation whenever needed.
In your case, it would be something like this:
@Component({
...
styleUrls: [...],
encapsulation: ViewEncapsulation.None,
host: {
'class': 'your-component-name' // <-- It should be unique for each component you have encapsulation off
}
})
export class YourComponent {
...
}
.your-component-name .icon {
// Your styles
}
A couple of notes on this approach. By following this pattern you are avoiding that the style from this component leak out (AKA bleed out) but you are not able to prevent that outside styles leak in (AKA bleed in), so on those cases, you need to use a higher specificity.
Upvotes: 1