简体   繁体   中英

Angular2: styling component dynamically inserted by the router

Searched for an answer for this and saw people struggling with this but no direct answer, especially with regards to the released 2.x version of Angular.

Suppose you have app.component.html with the following code:

<div>
  <router-outlet></router-outlet>
</div>

The router dynamically inserts your custom component, say my-component and (strangely enough) places that component as a sibling of router-outlet element like so:

<div>
  <router-outlet></router-outlet>
  <my-component></my-component>
</div>

Obviously, the router can place another component in there, so you can't rely on the name being my-component when creating styles in your app.component.css file.

So... How do you do this?

Why this matters? Why not just set the styles on the :host inside of the my-component CSS? Well, because not all styles belong there. For example, if the app.component decides that it's a flex container (ie, display: flex; ), that would mean that the my-component element should be styled as a flex item (ie, flex: 1 0 0; ). Placing the flex item style inside of the my-component seems like a bad practice because you are coupling it with the style of its parent component.

Chime in if you know the answer.

Thanks!

I haven't tried but I guess the adjacent sibling selector should allow you to do that

:host div + * {
  display: flex;
}

The key is /deep/ keyword:

在此处输入图片说明

the style will apply to whatever element followed by router-outlet.

在此处输入图片说明

Or make it specific to apply different style to known components.

:host /deep/ router-outlet + my-component {
    display: block;
    border: 10px solid black;
}

:host /deep/ router-outlet + my-component2 {
    display: block;
    border: 10px solid red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM