136

Route

const appRoutes: Routes = [
    { path: '', redirectTo: '/companies/unionbank', pathMatch: 'full'},
    { path: 'companies/:bank', component: BanksComponent },
    { path: '**', redirectTo: '/companies/unionbank' }
]

Component

const NAVBAR = [
    { 
        name: 'Banks',
        submenu: [
            { routelink: '/companies/unionbank', name: 'Union Bank' },
            { routelink: '/companies/metrobank', name: 'Metro Bank' },
            { routelink: '/companies/bdo', name: 'BDO' },
            { routelink: '/companies/chinabank', name: 'China Bank' },
        ]
    },
    ...
]

Example of link: http://localhost:8099/#/companies/bdo

I want to get String bdo in the example link above.

I'm aware that I can get the link by using window.location.href and split into array. So, I can get the last param but I want to know if there's a proper method on doing this in angular way.

Any help would be appreciated. Thanks

7 Answers 7

296

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

5
  • Is there a restriction where components loaded into a router-outlet of a parent component will see different ActiveRoute parameters - I've run into a case where the parent sees a parameter, but the contained components do not see the same parameter...
    – Neoheurist
    Dec 8, 2016 at 0:53
  • It was not working for me because I added the ActivatedRoute as a providers for my component. So, make sure you don't do that ! It's working like a charm with angular 4.2.4. Sep 3, 2017 at 17:22
  • 1
    For paramMap, you should be using params.get('bank') instead.
    – zurfyx
    Feb 8, 2019 at 19:26
  • What's the difference between this.route.snapshot.paramMap.get('bank'); and this.route.snapshot.params.bank;? Dec 10, 2019 at 10:00
  • with .get() you make sure you actually get the attribute - with .params.XXX you could get sth. from prototype chain - generic guidline: dont access properties but use the dedicated getter when there are some Oct 9, 2021 at 18:56
28

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

2
  • 1
    Why would switchMap be required here? Won't the subscribe get called on direct page load as well?
    – crush
    Oct 26, 2018 at 14:25
  • 4
    @crush From the docs linked above: "You might think to use the RxJS map operator. But the HeroService returns an Observable<Hero>. So you flatten the Observable with the switchMap operator instead. The switchMap operator also cancels previous in-flight requests. If the user re-navigates to this route with a new id while the HeroService is still retrieving the old id, switchMap discards that old request and returns the hero for the new id." Oct 29, 2018 at 18:20
3

This topic is already quite old, but still on top of my the search engine results. I am pretty sure the ways that have been shown here already work. But some of them are outdated or incomplete. So this is an up-to-date complete example, that hopefully helps you. I call the parameter receiving component PersonComponent. First part are your Routes most likely defined in app.module.ts (app-routing.module.ts):

const routes: Routes = [
{path: "/", component: HomeComponent}, 
{path: "person/name/:personName", component: PersonComponent}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

Notice the :personName in the route for the PersonComponent, this is the key we have to look for you can call it however you please. Next use this route in the HTML part of another (or the same) component:

<a routerLink="person/name/Mario">This is Mario</a>
<a routerLink="person/name/Luigi">This is Luigi</a>
<a routerLink="person/name/Bowser">This is Bowser</a>

Here the :personName is replaced with actual names. Last one is reading this parameter in the PersonComponent

import {ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-person',
  templateUrl: './person.component.html',
  styleUrls: ['./person.component.scss']
})
export class PersonComponent {

  constructor(route: ActivatedRoute) {
    const name = route.snapshot.paramMap.get('personName');
    console.log(name)
    //do whatever you want with it
  }
}

You can see that the :personName from the Routes is used as a key, to get the value from the paramMap.

1

You could try this for get route parameter:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {

  constructor(private activeRoute: ActivatedRoute) { 
    this.activeRoute.queryParams.subscribe((qp) => {
      console.log('Get Router Params:', this.activeRoute.snapshot.params.bank);
    });
  }

  ngOnInit(): void {
  }

}

You can check more details of the route URL here

0

Instead of going with paramMap you can also go fancy and use a Route Resolver although this might be a bit overkill and is usually used to fetch data during the navigation process...

setup resolver

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';

import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class LastUrlPathResolver implements Resolve<Observable<string>> {

  constructor(activatedRouteSnapshot: ActivatedRouteSnapshot){}

  resolve(): Observable<string> {
    return activatedRouteSnapshot.url[activatedRouteSnapshot.url.length-1]
  }
}

setup routes

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { NewsResolver } from './news.resolver';

import { TopComponent } from './top/top.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    component: HomeComponent
  },
  {
    path: 'top',
    component: TopComponent,
    resolve: { message: LastUrlPathResolver }
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

use it like

import { Component, OnInit } from '@angular/core';

import { ActivatedRoute } from '@angular/router';

@Component({ ... })
export class TopComponent implements OnInit {
  data: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.data = this.route.snapshot.data;
  }
}

find more here https://www.digitalocean.com/community/tutorials/angular-route-resolvers

0

Yes, surely you can get the param using the Angular way. Angular provides 2 ways to get the param value from the URL.

  1. Using the ActivatedRoute from @angular/router. Please check below code for the same. (https://angular.io/api/router/ActivatedRouteSnapshot)

    this.route.snapshot.paramMap.get('id');

  2. Using the paramMap Observable (https://angular.io/api/router/ParamMap)

    this.route.paramMap.subscribe((params: ParamMap) => { this.id = +params.get('id') });

Please check documentation links as well. And before using this.router please import ActivatedRoute from '@angular/router' for 1st option and import ActivatedRoute, ParamMap both for 2nd option. Below is the example.

import { ActivatedRoute} from '@angular/router'

import { ActivatedRoute, ParamMap } from '@angular/router'
0

Since Angular 16 you can bind route info to component inputs, see the link.

const appRoutes: Routes = [
    { path: 'companies/:name', component: CompaniesComponent },
]

Using components inputs:

@Component({})
export class CompaniesComponent implements OnInit {
    /* 
        We can use the same name as the query param
        Example url: http://localhost:4200/companies/my-bank
    */
    @Input() name?: string; // we can use the same name as the query param

    /* 
        Or we can use a different name
        Example url: http://localhost:4200/companies/my-bank
    */
    @Input('name') queryParam?: string; // we can also use a different name

    ngOnInit() {
        // do something with the query
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.