How to get the current URL/Route in Angular?
// Current Path: company
// Data: { title:
'Company' }
// Siblings
With pure JavaScript:
console.log(window.location.href)
Using Angular:
this.router.url
The
Examples in details -
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: 'The href link is : {{href}}'
})
export class Component {
public href: string = null;
constructor(private router: Router) {}
ngOnInit() {
this.href = this.router.url;
console.log(this.href);
}
}
To
get the route segments:
import { ActivatedRoute, UrlSegment } from '@angular/router';
constructor( route: ActivatedRoute) {
}
getRoutes() {
const segments: UrlSegment[] = this.route.snapshot.url;
}
//OR
//You can inject
ActivatedRoute and access more details using its snapshot property.
constructor(private route:ActivatedRoute) {
console.log(route);
}
OR
@Component({...})
export class CompanyComponent implements OnInit {
constructor( private router: Router, private route: ActivatedRoute) {}
ngOnInit() {
// Parent: about
this.route.parent.url.subscribe(url => console.log(url[0].path));
this.route.url.subscribe(url => console.log(url[0].path));
this.route.data.subscribe(data => console.log(data));
console.log(this.router.config);
}
}
Reference
URL -
https://angular.io/api/router/ActivatedRoute#description
https://angular.io/api/router/ActivatedRoute