KevinTale
KevinTale

Reputation: 1888

Get current Component in Angular 5

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.

Upvotes: 1

Views: 4544

Answers (2)

user4676340
user4676340

Reputation:

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)

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657909

<router-outlet> provides some events like

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

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

Upvotes: 7

Related Questions