Angular2 change parent styles outside component

I would like to change component styles outside the scope of my current component. The markup in my app.component.html is as follows:

<app-nav></app-nav>
<div id='content-container'>
<router-outlet></router-outlet>
</div>

I want to change the styles of the class main-navin the app-nav component from the "home component", which is loaded from the route. I use routerLinkin the navigator, and I found that if I add encapsulation: ViewEncapsulation.Nonein home.component.ts, I can change the styles of this class in the app-nav component, but the changes are applied only once, and if I go for other routes using routerLinkI canโ€™t undo the changes (it seems that css is loaded or applied only once - when the component is initialized / appears in the view)

+4
source share
2 answers

change component styles outside my current component area

Before I say anything else, this is very discouraging. Components should be standalone objects that can be reused in your project or even in other projects. By creating a component that changes something else in the system only through CSS, you create a tight connection that is difficult to see from the code immediately, which leads to complex debugging of errors and other errors.

If you want to change yours app-nav(or main-nav, as you will find later, I'm not sure if this is my mistake) based on the current route, you must do this by entering ActivatedRouteand querying it to determine the specific version of the header you want.

- , , .

, ,

routerLink <

, DOM , , , . Angular , , . .

(, css / - / )

.

+2

css . : : host-context .

. https://angular.io/guide/component-styles#special-selectors

: ( ).

. , CSS , , .

-: host-context(), , : host(). : host-context() CSS- -, document root. : host-context() .

+1

Source: https://habr.com/ru/post/1686320/


All Articles