Parsing URL Parameters in Angular  Components

Simple tasks are often confusing the first time you handle them in Angular. There are many answers to most of these simple questions, but many of them are overly complex and confusing to understand. If you’re just starting out with Angular, or have recently made the switch from AngularJS, you’ll most likely need to work with dynamic route parameters. Here’s a very simple overview explaining how to get a URL parameter from a component route, and also query parameters as well.

Create a Dynamic Route

The first step here is to create a dynamic route for a component, like a basic password reset form. In Angular, the best practice is to load and configure routes in a top-level module, one that us then imported by your root AppModule.

It will likely look something like this:

// Routes
const routes: Routes = [ {
    path: 'example-params/:first/:second',
    component: ExampleParamsComponent,
} ]

// Root AppModule
@NgModule( {
    imports: [
        BrowserModule,
        RouterModule.forRoot( routes ),
    ],
    declarations: [
        MainAppComponent,
        ExampleParamsComponent,
    ],
    bootstrap: [ MainAppComponent ]
} )

Capture URL Parameters from a Component

Once you have the route configured, you’ll handle that URL from your ExampleParamsComponent component. Inside of the component you’ll work with Angular’s ActivatedRoute class, which provides access to route parameters through its params property.

Below is a simple example component that should provide you with an understanding for how to get a param from a URL in Angular. Pay close attention to the use of activatedRoute, this is a reference to Angular’s ActivatedRoute, which we’ll use to capture dynamic URL parameters and query parameters from within our component.

/**
 * Password Reset Component
 *
 * <app-example-params>
 */
import { ActivatedRoute, Params } from '@angular/router';
import { OnInit, Component } from '@angular/core';

@Component( {
    selector: 'app-example-params',
    templateUrl: '/example-params/index.html',
} )

export class ExampleParamsComponent implements OnInit {

    // Dynamic parameters for this component's route: /example-params/:first/:second
    routeParams: Params;

    // Query parameters found in the URL: /example-params/one/two?query1=one&query2=two
    queryParams: Params;

    constructor(
        private activatedRoute: ActivatedRoute
    ) {
        this.getRouteParams();
    }

    ngOnInit() {}

    // Store parameter values on URL changes
    getRouteParams() {

        // Route parameters
        this.activatedRoute.params.subscribe( params => {
            this.routeParams = params;
        });

        // URL query parameters
        this.activatedRoute.queryParams.subscribe( params => {
            this.queryParams = params;
        });
    }
}

We’re doing two things here in the getRouteParams() method:

  1. Get and store route parameters passed to the component’s URL as routeParams
  2. Get and store any query parameters found on the URL as queryParams

We’re subscribing to the params and queryParams Observables provided by Angular’s ActivatedRoute class. When a route parameter or URL query parameter changes, we capture the value by subscribing to changes like this. Each defined parameter, like :first and :second, will be stored as a property on the params object provided as a result. params is an instance of a Params type, which stores a collection of parameters. The end result of the getRouteParams() method is that we’ll have two objects to work with in our component’s template:

  1. routeParams – Object with every route parameter for the component
  2. queryParams – Object with every URL query parameter for the component

Dumping Output in a Template

If you’d like to dump the output of this to a template, use the following HTML inside of /example-params/index.html:

<div class="app-example-params">
    <h2>routeParams</h2>
    <pre>{{ routeParams|json }}</pre>

    <h2>queryParams</h2>
    <pre>{{ queryParams|json }}</pre>
</div>

This will dump both of our params objects for debugging purposes.

Capturing Parameters from Parent Component

If you need to capture route parameters from a parent component you can make use of an ActivatedRoute’s parent property to statically get the values from the URL. This will only provide you with the route parameters present when the component loads though, because it’s a reference to the parent component’s snapshot. To do this you could use something like this:

// Dynamic parameters from a parent component: /app/:section/example-params/:first/:second
parentRouteParams: Params;

// Get parameters from a parent component
getParentParams() {

    // This would store the value of the :section parameter
    this.parentRouteParams = this.activatedRoute.parent.params;
}

Conclusion

Hopefully this overview gives you a solid idea of how to get params from a URL in Angular. The ActivatedRoute class provides us with additional functionality beyond this. I’d highly suggest reviewing the documentation on Angular.io to gain a solid understanding of it.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.