SnailCoil
SnailCoil

Reputation: 808

Change URL Path Parameter in Angular 2 Without Changing Active Route

I'm trying to figure out a way to update a path parameter in my URL without changing the currently active route. For example, say I have the following routes:

{
    path: 'pages/:pageId',
    component: PageComponent,
    children: [
    {
        path: 'sections/:sectionId',
        component: PageSectionComponent,
        children: [
        {
            path: 'details',
            component: PageSectionDetailsComponent
        }]
    }]
}

The problem I'm trying to solve is, when somebody changes the :pageId, I want to keep their active route while changing the URL. So if they change :pageId from 999 to 777, their route should change from:

pages/999/sections/123/details   =>   pages/777/sections/123/details
pages/999/sections/123           =>   pages/777/sections/123

Additionally, I need to make this work for :sectionId. For example, navigating from :sectionId 123 to 456:

pages/999/sections/123/details   =>   pages/999/sections/456/details
pages/999/sections/123           =>   pages/999/sections/456

There are several child routes in my project that I omitted, so absolute links would be very difficult to maintain. I'm hoping I can somehow use the current ActivatedRoute, change the single parameter I'm updating, then navigate to that route using the Router.

Any help is greatly appreciated!

Additional info:

I'm using Angular 4.0.0

There's a similar question that gets at the core problem I'm trying to solve, but it's out of date: Change a single route parameter on the current route in Angular 2

Upvotes: 2

Views: 5431

Answers (1)

DeborahK
DeborahK

Reputation: 60568

You can update to the new required parameter in code or in the HTML ... whichever makes most sense in your application.

In the HTML, you'd do it with a routerLink directive:

<a [routerLink]="['/products', product.id]">{{product.productName}}</a>

Or with code like this:

this.router.navigate(['/products', this.product.id]);

Or with your example:

this.router.navigate(['/pages', this.pageId, '/sections', this.sectionId]);

(I think I misunderstood the question the first time.)

Upvotes: 3

Related Questions