Working with Params in Angular

angular params

While working with routes in angular, sometimes we might need to fetch some information from the url that shows up in the browser.
Params, QueryParams and Fragments are the bits of information that can be fetched from the route url.

This is one part of the 3 part series of the subject – Working with Params, QueryParams and Fragments in Angular
In this part, we are going to work with Route Params in Angular.

Params

Params form the dynamic part that is available as a part of the url itself.

Lets consider some dynamic route that we create in angular for showing user information based on ID
http://localhost/users/:user_id
Here :user_id stands for the dynamic part of the url, so we can have
http://localhost/users/102
http://localhost/users/105 …

So we may need these user_id from the url to make requests, either from the frontend data itself or to the backend.

To fetch the user_id from the url, in the component that opens up the given route, we need to import ActivatedRoute that is part of the @angular/router package.

user-edit.component.ts

export class UserEditComponent {
    constructor(private _activatedRoute: ActivatedRoute) {
        const userID = this._activatedRoute.snapshot.params['user_id'];
        // For http://localhost/users/102, it would log 102
    }
}

One gotcha to keep in mind is that userID would be a string as the route itself is a string. To make a workaround, just typecast the user_id.

const userID = +this._activatedRoute.snapshot.params['user_id']; // This would give userID as a number

As we are using this params snapshot from the constuctor itself, there possibly might be situations, when the top route would change from inside the component itself.
user-edit.component.ts

onClick() {
    changeRouteTo('http://localhost/users/203'); // Dummy function that would change route to this url.
}

In this case, our userID information wouldn’t change as the component has no idea that the url has changed in the browser. In this case, we need to listen to the events fired by the ActivatedRoute.
For this we need to subscribe to changes in the ActivatedRoute’s params attribute

this._activatedRoute.params.subscribe((params: Params) => {
    userID = +params['user_id'];
});

This will give the updated id even if the page component hasn’t changed.

You can find the other 2 parts here:
2. Working with QueryParams in Angular
3. Working with Fragments in Angular

Leave a Reply