I want to set a class active
on a div (part of a component) if a variable is true (workspace.active
here) AND an ancestor element has class .home
.
Something like:
<div [ngClass]="{'active': workspace.active && ':host-context(.home)', }">
Can I use somehow this pseudo selector :host-context
in such an conditional expression for ngClass ?
Details:
I want to use same component in two use cases. Only some css properties should be different on the two cases. So I want to customize a css class set on a div on my component based on decision: "there is an ancestor home
in the dom tree or not" - this should differentiate the two use cases.
I could do things like this in css:
:host-context(.home) .active {
background-color: #405976;
}
but then all selector combinations containing .active
class should be combined also with :host-context
and I I don't want to grow the complexity in css as it is already complex.
I would prefer to just set the class .active
based on the condition. In css file !, not in code. (This is why :host-context
exists in the end.)
In angular you should not make any logical decisions in the code based on the html content properties such as classes or attributes, but vice versa - you should render classes and attributes in html based on data bindings. That's the main idea of angular - rendering view based on data bindings. Component's code should not really care too much about view structure.
So, in this case if your class should be based on some external information you need to @Import() that data through data bindings into your component and then use component properties in the ngClass directive. Yes, it moves logic into the component instead of html/css, but that's where it's supposed to be anyway: in the model/controller code, not in the view markup. Also, this way it will be much more convenient to test such a component.