I want to get the last part of my url for example from /item/:id/edit
I want to get edit
or /edit
.
I found this Question here but this doesnt work because I want to run this Code in the parent component and the whole url I get from this Code is /item/:id
.
How can I get the last part from it?
I have the solution for getting the last part of URL
url = '/item/:id/edit'
url.split('/').pop();
Explain:
.split('/')
means split the string which
is separated by '/' to an array of substrings.pop()
means removes the last element of an
array, and returns that element.split('/').pop()
means split the
string which is separated by '/' to an array of substrings then
removes the last element of an array and return that elementI hope this help
You can use ActivatedRoute interface, it contains the router state tree within the angular app’s memory.
The parent
property represents the parent of the route in the router state tree,
while the snapshot
property is the current snapshot of the route and url
is an
observable of the URL segments and it matched by this route.
Step 1: Import ActivatedRoute
import { ActivatedRoute } from '@angular/router';
Step 2: Inject ActivatedRoute in constructor.
constructor(private route: ActivatedRoute) { }
Step 3: Call it in Oninit lifecycle hook
constructor(private route: ActivatedRoute){}
ngOnInit() {
this.route.parent.snapshot.url[2].path;
}
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