18

So I need somehow check if I am on home page and do something and in other pages don't do that. Also that component imported on all of pages.

How can I detect on that component if I'm on home page???

Thanks

Aram Mkrtchyan
  • 2,690
  • 4
  • 31
  • 47
  • 3
    Possible duplicate of [How to get current route](http://stackoverflow.com/questions/34597835/how-to-get-current-route) – Adam Mar 01 '17 at 17:40

7 Answers7

47

Try this,

import { Router } from '@angular/router';
export class MyComponent implements OnInit {

    constructor(private router:Router) { ... }

    ngOnInit() {
        let currentUrl = this.router.url; /// this will give you current url

        // your logic to know if its my home page.
    }

}
Vivek Singh
  • 1,113
  • 10
  • 20
  • 11
    except that this always shows `/` as the URL... ie it is not showing the current page, only the root of the site – Serj Sagan May 20 '17 at 09:45
  • Works correctly for me. It's displaying /home when I'm in HomeComponent. – anonym Jun 09 '17 at 08:31
  • @SerjSagan you must be having `{ path: '', component: RootComponent }` as the root page... – Vivek Singh Jun 09 '17 at 08:53
  • { path: 'about', component: About, data: {title: 'About'} } have this but still im getting / – SameerShaik Jun 11 '17 at 11:48
  • 6
    I think there is some confusion here related to where this code is used. If you use it in the `app.component` which hosts the `` tag it will always return `/` while in the child components it works properly. – Raul A. Jun 14 '17 at 04:10
  • 7
    @RaulA That's the issue I'm having. Do you know of a way to get the non-root current route from the app component? – Yona Appletree Jun 29 '17 at 22:43
  • 2
    According to [Angular Style Guide](https://angular.io/guide/styleguide): Dont mark private variables with an _underscore – Mick Aug 25 '17 at 09:54
  • 1
    @YonaAppletree - I think [this](https://stackoverflow.com/a/43513784/185123) answers how to get the route in the app component – spottedmahn Jan 26 '18 at 14:36
40

Try it

import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({...})

export class MyComponent {

  constructor(private router:Router) {

    router.events.subscribe(event => {

      if (event instanceof NavigationEnd ) {
        console.log("current url",event.url); // event.url has current url
        // your code will goes here
      }
    });
  }
}
Pankaj Anupam
  • 580
  • 4
  • 13
5

Try any of these from the native window object.

console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);

NOTE: DO NOT USE THIS IN SERVER SIDE RENDERING

Sanket Berde
  • 6,555
  • 4
  • 35
  • 39
2

You can use Angular Location Service.

import { Location } from '@angular/common';

You can access the path using:

location.path();
Sarat Chandra
  • 5,636
  • 34
  • 30
0

If you want the complete URL, use LOCATION instance as follows :-

([Location][1])location.href = https://test-mydomain.com/#/securelogin?name=batman

& if you want relative URL, use ROUTER instance follow :-

this.router.url = securelogin?name=batman

Follow the complete snippet as follows based on angular 4:-

constructor( private router: Router) {
  console.log(this.router.url);
/**
* securelogin?name=batman
*/

  console.log(location.href);
/**
* https://test-mydomain.com/#/securelogin?name=batman
*/
}
0

I was about to answer this question but I have the same answer with BigBrother. This answer is for those who uses "#" on their URL as it only returns "/" on some router location code.

This is a sample code of one of my project:

this.router.events.subscribe((event)  => {
  if(event instanceof NavigationEnd) {
      this.currentPage =  event.url;
      if ( event.url != '/admin') {
        setTimeout(()=>{
            this.modalRef = this.modalService.show(ModalSurveyComponent,this.config);
        }, 3000);
      }
  }
});

So Pop up will only show if the current route is not "/admin"

-3
import { RouterStateSnapshot } from '@angular/router';

constructor(private state: RouterStateSnapshot) {
    console.log("Current Url Path", state);
}
  • 5
    While this snippet may answer the question some explanation would certainly improve it. – Joshua Drake Aug 10 '17 at 21:06
  • 3
    In 4.4.4, [RouterStateSnapshot](https://github.com/angular/angular/blob/4.4.4/packages/router/src/router_state.ts#L314-L350) is not an injectable service. – Maxime Morin Oct 12 '17 at 18:30