Search code examples
javascriptangulartypescriptangular-routingangular-router

How can I change url parameters in Angular?


For example I have a url /videos/5 which shows page 5 of my videos page. How can I use the Angular router to change to page 3 for example. Is there a way to 'relatively navigate' like without having to pass videos to the url.

Something like:

this.router.navigate([`/${pageNumber}`])

(page number is the number of the page I want to go to like /videos/3)

I looked around but can't find a solution I tried

this.router.navigate([`../${pageNumber}`], { relativeTo: this.activatedRoute.parent })

But it's giving me errors.

How to achieve this with Angular router and relative urls.


Solution

  • Yes, you can use relativeTo with instance of ActivatedRoute, like this:

    import { ActivatedRoute, Router } from '@angular/router';
    
    ...
    
    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) { }
    
    ...
    
    this.router.navigate([`../${pageNumber}`], { relativeTo: this.activatedRoute })