Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2-router: How to only change a parameter of a route?

I want to have the following routes in my application:

export const routes: Routes = [
    { 
       path: ':universityId', 
       component: UniversityComponent,
       children: [
           { path: 'info', component: UniversityInfoComponent },
           { path: 'courses/:status', component: CoursesByStatusComponent }
       ]
    }
]

Being on /1/info or /1/courses/open url, how do I change :universityId only from UniversityComponent?

Simple router.navigate(['../', 2], {relativeTo: currentRoute }) won't do because it redirects to /2, losing all other information. Using '../2/courses/open is also not an option - I can be on any child route at that moment. Best I could come up with is:

const urlTree = this.router.parseUrl(this.router.url);
urlTree.root.children['primary'].segments[0].path = '2';
this.router.navigateByUrl(urlTree);

but it's kind of ugly

like image 690
Alex Shevnin Avatar asked Oct 26 '16 11:10

Alex Shevnin


People also ask

What is Route params?

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

How do I access route parameter?

The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .

What is the difference between ActivatedRoute and ActivatedRouteSnapshot?

Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.

What is Route reuse strategy?

BaseRouteReuseStrategylink This base route reuse strategy only reuses routes when the matched router configs are identical. This prevents components from being destroyed and recreated when just the fragment or query parameters change (that is, the existing component is reused).


1 Answers

This is very simple. You can simply try to use this.router.navigate(["../2", "courses", "open"], {relativeTo: this.route});

(or)

this.router.navigate(["../2", "courses/open"], {relativeTo: this.route});

This will redirect you to ../2/courses/open.

like image 59
Srilatha Patil Avatar answered Oct 17 '22 01:10

Srilatha Patil