You can achieve this through the built-in ActivatedRoute
service, your “one-stop shop for route information,” as the documentation says.
First you need to enter the service in your component constructor. Assuming you have a Todo component, a Birthday component, in any case, the constructor would look like this:
constructor(private currentRoute: ActivatedRoute, private router: Router) { }
Then, in your ngOnInit () function, you need to subscribe to your url property of the ActivatedRoute instance, which is observable:
ngOnInit() { this.currentRoute.url .subscribe(routeParts => { this.periodArray = []; for (let i = 1; i < routeParts.length; i++) { this.periodArray.push(routeParts[i].path); } }); }
The reason your component route is provided as an observable is because it can take several different routes during the component life cycle. As in your case, "/ todo / 2017" or "todo / 2017/01", etc. Your component will be created only once, ngOnInit () will also be called only once, but by subscribing to the activated activated Route.url, you will always receive a notification about the current route.
The above code block fills the array with everything except the first part of the url from the activated route, which gives you all the parameters passed, except for the initial segment "/ todo" or "/ birthday".
Now you can go to another component by simply adding the desired path at the beginning of this array of parameters, for example:
navigateBirthdays() { this.periodArray.unshift('/birthday'); this.router.navigate(this.periodArray); }
Here is the complete code for the Todo component and its template:
todo.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ templateUrl: './todo.component.html', }) export class TodoComponent implements OnInit { periodArray = []; constructor(private currentRoute: ActivatedRoute, private router: Router) { } ngOnInit() { this.currentRoute.url .subscribe(routeParts => { this.periodArray = []; for (let i = 1; i < routeParts.length; i++) { this.periodArray.push(routeParts[i].path); } }); } navigateBirthdays() { this.periodArray.unshift('/birthday'); this.router.navigate(this.periodArray); } }
todo.component.html
<p> List of Todo items for {{periodArray.join("-")}} </p> <button (click)="navigateBirthdays()">Show Birthday items</button>
The birthday component would look almost identical. The above allows you to switch between / todo / 2017/1/3 and / birthday / 2017/1/3, as well as between / todo / 2017 and / birthday / 2017, etc. without configuring any specific routing rules.
Note: for optional parameters, it is usually better not to include them in the URL path, but to provide them as an optional route object - see this section of the documentation.