Jake
Jake

Reputation: 26117

Angular - Get Component name from a URL

I have routes defined this way in app-routing.module.ts:

const routes: Routes = [
  {
    path: 'abc/:id', component: AbcComponent
  },
  {
    path: 'xyz/:id/tester/:mapId', component: XyzComponent
  },
  { path: '**', redirectTo: '/page-not-found', pathMatch: 'full'}
]

I would like to get the component name based on a URL in app.component.ts

Ex: If a user navigated to http://myapp.com/abc/123 I would like to the get the component name, which in this case would be AbcComponent

If a user navigated to http://myapp.com/xyz/123/tester/456 I would like to the get the component name, which in this case would be XyzComponent

How can I get that?

I tried to use ActivatedRoute, but it doesn't seem to work, as I get Cannot read property 'component' of null.

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   console.log(this.activatedRoute.routeConfig.component.name)
}

Upvotes: 3

Views: 2555

Answers (2)

A.khalifa
A.khalifa

Reputation: 2496

Try this it work for me

constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
 this.checkRoute()
}

checkRoute()
{
   var snapshot = route.snapshot;
   console.log(snapshot._routeConfig.component.name); 
}

Hope useful

Upvotes: 0

pzaenger
pzaenger

Reputation: 11984

You could add the name of each component to the data object of the accordant route, like:

{
  path: 'abc/:id',
  component: AbcComponent,
  data: {
    name: 'AbcComponent'
  }
}

And then getting its value like demonstrated here:

ngOnInit() {
  this.route.data.subscribe((data: { name: string }) => {
    console.log(data);
  });
}

Edit:

I have created a stackblitz. Open the console and click on Catalog.

Upvotes: 1

Related Questions