Let's suppose I've got 3 urls: /:projectId/info
, /:projectId/users
, /:projectId/users/:userId/profile
. All of them have param projectId
. UI has a component to switch from one project to another. So I need:
So I need something like this.router.replaceParam(currentUrl, {projectId: 'project_id_2'})
which will transform /project_id_1/users/user_id_1/profile
into /project_id_2/users/user_id_1/profile
(and any other URL with :projectId
param)
I thought it's a simple and common problem but didn't find a solution in 1 hour. Suggested here solution doesn't work as noted in the last comment
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 .
The $routeParams service allows you to retrieve the current set of route parameters. Requires the ngRoute module to be installed. The route parameters are a combination of $location 's search() and path() . The path parameters are extracted when the $route path is matched.
navigateByUrl is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas router. navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.
Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button. Consider the following template, where routerLink attribute added to the anchor tag. The routerLink directive on the anchor tags give the router control over those elements.
To navigate to particular link from current url, you can do something like this,
constructor(private route: ActivatedRoute, private router: Router){} ngOnInit() { this.route.params.subscribe(params => { // PARAMS CHANGED .. let id = params['projectid']; }); } navigate(){ this.router.navigateByUrl(this.router.url.replace(id, newProjectId)); // replace parameter of navigateByUrl function to your required url }
On ngOnInit function, we have subscribed to params so we can observe and executes our statements on any change in url parameter.
Edit
Case: where ids can be same
constructor(private route: ActivatedRoute, private router: Router){} projectId:string; userId: string; ngOnInit() { this.route.params.subscribe(params => { this.projectId = params['projectid']; this.userId = params['userId']; }); } navigate(){ // for /project/:projectId/users/:userId/profile this.router.navigate(['/project', this.projectId, '/users', this.userId, '/profile']); }
You can use either HTML Or Ts
1 > In HTML
[routerLink]="['../info']" Or [routerLink]="['../users']" like this etc....
2 > In Typescript
this.router.navigate(['../users'], { relativeTo: this.activatedRoute });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With