Angular 6 URL Parameters

How To Get Current URL/Route in Angular?

How to get the current URL/Route in Angular?

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));
 // Current Path:  company
  this.route.url.subscribe(url => console.log(url[0].path));
 // Data:  { title: 'Company' }
  this.route.data.subscribe(data => console.log(data));
 // Siblings
  console.log(this.router.config);
}
}

Reference URL -
https://angular.io/api/router/ActivatedRoute#description
https://angular.io/api/router/ActivatedRoute
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^