How to apply css class to a component element when it's created by router-outlet?

Assuming you always want the class applied to this component, you can use host in your component metadata:

@Component({
  selector:'project',
  host: {
      class:'classYouWantApplied'
  }
})

Resulting in:

<app>
    <router-outlet></router-outlet>
    <project class="classYouWantApplied">...</project>
</app>

use the adjacent sibling selector and the * wildcard to select the element immediately following the router-outlet


styles.css

router-outlet + * {
  /* your css */
}

enter image description here


The key is /deep/ keyword:

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

This works without any extra configurations.

:host /deep/ router-outlet + * for whatever component dynamically created by Angular Router.

Edited 2018/3/5:

Since Angular 4.3.0 made /deep/ deprecated, its suggested alternative is ::ng-deep. And there were a long discussion about this.