3

I want to apply styling for each component, what i am looking is I want to get the current component selector name and pass it as class name like this

<div [class]="component-slector-name">
<router-outlet></router-outlet>
</div>

so that for every active component I get its selector and set it to div tag for custom css styling..

Does anyone know how to do this ?? Thanks in advance for time and support.

mpunit30
  • 381
  • 9
  • 26
  • 1
    Why do you want to pass class name? Since, every component has its own name, you can just write styles for your element like this `component-selector-name { // your css rules }` – Bunyamin Coskuner Nov 13 '17 at 07:01
  • Also, each component can have its own dedicated, isolated CSS rules, though the styles or styleUrls property of its decorator. – JB Nizet Nov 13 '17 at 07:07
  • Ya but when i am applying css to its dedicated css file it's not getting applied, and i got link through search regarding the view Encapsulation, on using that the style is getting set globaly. That is throughout application I am settings .container{padding-left:240px} but for login content i want .container{padding-left:0px} , so when i am using ViewEncapsulation the style is getting applied globally. – mpunit30 Nov 13 '17 at 07:12
  • Also my app.html is like
    now for login component I want to set the {padding-left:0px} for
    and for whole application i want {padding left:240px}
    – mpunit30 Nov 13 '17 at 07:16
  • https://angular.io/guide/component-styles#host. But again, even with a global stylesheet, you just need `main { ... }`. Adding a class is unnecessary. – JB Nizet Nov 13 '17 at 07:25
  • I have added main{pading-left:240px; } to my global stylesheet, but how to set it for the login component as i have even tried ::ng-deep and :host as well as ::host-context(){} nothing works for me. Or i am making some mistake for applying host. So can you help me out in achieving it.... Or can you share the code.... – mpunit30 Nov 13 '17 at 07:37
  • @ JB Nizet can you share the code or help me to apply the :host ... – mpunit30 Nov 13 '17 at 07:43

1 Answers1

5

There are different ways to achieve it.

Here is one option:

*.html

<div [class]="activeSelector">
  <router-outlet (activate)="onActivated($event)"></router-outlet>
</div>

*.ts

activeSelector: string;

constructor(private resolver: ComponentFactoryResolver) {}

onActivated(component) {
  this.activeSelector = 
        this.resolver.resolveComponentFactory(component.constructor).selector;    
}
yurzui
  • 205,937
  • 32
  • 433
  • 399