javascriptangularangular2-routing

How to get parameter on Angular2 route in Angular way?


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 url: http://localhost:8099/#/companies/bdo

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

I'm aware that I can get the url by using window.location.href and split into an array. In that way, I can get the last parameter of the url above. However, I wanted to know if there's a proper way to do this in Angular.

Any help would be appreciated. Thanks


Solution

  • 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"