Angular2, How to get the current active component

2019-02-18 22:45发布

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.

1条回答
等我变得足够好
2楼-- · 2019-02-18 23:31

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;    
}
查看更多
登录 后发表回答