Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Get current route

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

like image 708
Aram Mkrtchyan Avatar asked Mar 01 '17 17:03

Aram Mkrtchyan


People also ask

How do I find the URL of a route?

There are many ways by which you can get a current Route or URL in Angular. You can use the router service, location service or window object to get the path. You can also listen to changes to URL using the router event or URL change event of the location service.

How do I use ActivatedRoute?

Step 1: Import ActivatedRoute from Router module. import { ActivatedRoute } from '@angular/router'; Step 2: Inject ActivatedRoute in constructor. Now we have id in edit_quiz.

What is NavigationEnd in Angular?

NavigationEndlinkAn event triggered when a navigation ends successfully. class NavigationEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string) type: EventType.

What is Routerstatesnapshot in Angular?

RouteStateSnapshot is an immutable data structure representing the state of the router at a particular moment in time. Any time a component is added or removed or parameter is updated, a new snapshot is created.


2 Answers

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.
    }

}
like image 127
Vivek Singh Avatar answered Oct 08 '22 10:10

Vivek Singh


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
      }
    });
  }
}
like image 20
Pankaj Anupam Avatar answered Oct 08 '22 10:10

Pankaj Anupam