1

I need to inject css classes based on current component. i.e: if I'm currently on LoginComponent, I need to inject login class into the app.component.html (the greater parent of my app). Like so:

<div class="content login">
    <router-outlet></router-outlet>
</div>

I don't know what the best practices are to handle this. I could also based the injection on url. i.e: if url is xxx./login, then inject login css class.

Any ideas?

Thanks.

KevinTale
  • 1,658
  • 3
  • 25
  • 47
  • See also https://stackoverflow.com/questions/47258429/angular2-how-to-get-the-current-active-component-selector-to-use-it-as-class-gl – yurzui Dec 11 '17 at 15:45

2 Answers2

7

<router-outlet> provides some events like

<router-outlet (activate)="currentComponent = $event"></router-outlet>

See also https://angular.io/api/router/RouterOutlet

yurzui
  • 205,937
  • 32
  • 433
  • 399
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

First, make a mother class with a getter like this

export class ClassNamer {
  get className() { return this.constructor.name.toLowerCase().replace('component', ''); }
}

This will return the class name, to lower case, without the component word.

In your classes, you must do

export class LoginComponent extends ClassNamer { ... }

Now, in your HTML, all you have to do is

<div class="{{className}}"></div>

Voilà !

EDIT If you want to apply the class to the parent component, then in your ClassNamer, add an Output, that emits the className to the parent (but keep in mind that a router outlet isn't a "parent" per se)