I want the contents of an Angular component to change when a certain class exists in one of the parent components/elements. Very similar to the :host-context()
CSS selector, but in the TypeScript component code.
Using :host-context(.the-class)
, I can control the visibility of elements in my component, but this will only modify the style of the component. I also want to modify the behavior.
I have also tried the JQuery route with $(this.element.nativeElement).parents().hasClass("the-class");
. This works reasonably well, but I would prefer a more declarative/Angular approach.
@Component({
template: `
<p>{{text}}</p>
`,
styles: [`
:host-context(.the-class) p {
color: red;
}
`]
})
class MyComponent {
text: string;
/*
Change content of 'text' if 'the-class' can be found
in any of the parents here somewhere.
*/
}
So... What is the best way to do this "the Angular way", without resorting to JQuery or native DOM selectors? I realize that this may not be a common use-case, as it would break component isolation and so on. But I figured since the :host-context
selector exists for styling, there must be something similar for the controller.