gsiradze
gsiradze

Reputation: 4733

Get current component name

Is that possible to get current component name?

for example if I have localhost:3000/en/mycomponent and I'll to this.router.url it returns /en/mycomponent which is /language/component

I want to make redirect on language change.

I can make

this.router.navigate([this.lang, my component here]);

But how can I get current component from routing?

Upvotes: 20

Views: 53959

Answers (11)

Dor Levi
Dor Levi

Reputation: 361

To get the current component I use this code for Angular 13:

import { ActivationEnd, Router } from '@angular/router'; 

constructor(private router: Router) { }

ngOnInit(): void {
 this.router.events.subscribe((val) => {
   if (val instanceof ActivationEnd) {
      const [,componentName] = val.snapshot.component.toString().split(" ");
      console.log(componentName);
   }
  });
 }

Upvotes: 0

Chamila Maddumage
Chamila Maddumage

Reputation: 3876

Best way to get the component name is using the constructor.

this.constructor.name

Upvotes: 4

Corey Downie
Corey Downie

Reputation: 4769

It is possible, but in a production build the name will differ from during dev, so don't use it for anything valuable

If you need to check 'which' component is currently in the route for example it's best to use typeof rather than checking for the name

const onComponent = typeof this.activatedRoute.snapshot.routeConfig.component === typeof MyCustomComponent

Upvotes: 1

Ravimallya
Ravimallya

Reputation: 6610

You can get the current component name from the 'ActivatedRoute' module like this:

    const compName = this.activatedRoute.snapshot.routeConfig.component.name;

use the above either in onInit or constructor call. It's working fine in angular 6+. Not sure about the older versions.

Upvotes: 3

Boris Jenicek
Boris Jenicek

Reputation: 203

Angular CLI:

You can access the component name from the constructor:

 console.log('this', this.constructor.name);

 this.constructor.name; // Component name

Upvotes: 11

Gollm
Gollm

Reputation: 130

Angular 8

This returns name of current Component each time, the shown Component changes.

constructor(private router: Router) {
    router.events.subscribe((val) => {
        if (val instanceof ActivationEnd) {
            console.log('componentName', val.snapshot.component['name']);
        }
    });
}

Upvotes: 5

Rajesh Choudhary
Rajesh Choudhary

Reputation: 115

@Madhu Ranjan answer.

His approach will not work with dot notation. We will get an error like, Property 'name' does not exist on type 'string'.

As it expects component to be string. As we used dot notation. On top of that, we are accessing a name string property on component string.

As dot notation expects everything to be string after dot. But here in route.component.name (component.name is not a string). It will try to find component.name on route object.

So it's better to go with bracket notation in this case.It will evaluate and convert given expression to string.As component is a function on route object.

When I tried with:

console.log('current component rendered', route.['component']['name']);
                    or
console.log('current component rendered', route.component['name']);

I was successful in getting component name.

Upvotes: -1

Plastikaweb
Plastikaweb

Reputation: 31

You can get the component name with dot notation like that:

let state: ActivatedRouteSnapshot = routerState.root;

while (state.firstChild) {
  state = state.firstChild;
}

const stateComponent = <any>state.component;
const component = stateComponent ? stateComponent.name : '';

Upvotes: 0

Ryan_D
Ryan_D

Reputation: 314

I was running into the same issue as above and was able to use the following to retrieve the component name: this.route.routeConfig.component.name. This returned a string value that we can compare.

Upvotes: 18

slaesh
slaesh

Reputation: 16917

Only that component name isn't enough.. you may want the additional options and so on..

If the first segment is always your language, do it like this:

let urlSegments = this.route.url.split('/');
urlSegments[1] = this.lang;
this.router.navigate(urlSegments.join('/'));

Upvotes: 3

Madhu Ranjan
Madhu Ranjan

Reputation: 17944

You may get the component name like below,

export class MyComponent{

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {
    // Below will result in MyComponent
    console.log(this.route.component.name);         
  }
}

Having said that Routing is based on path rather the component name.

Hope this helps!!

Upvotes: 5

Related Questions