Get activated route from angular 2 routing

Viewed 10748

Hi so I have declared my route with the id like this {path: 'spreadsheet/:id', component: ContactParent} so here I can get the id by using ActivatedRoute but how I can get spreadsheet, if I do this.router.url it gives me spreadsheet/20 but I only need spreadsheet

4 Answers

Try this...

constructor( private route: ActivatedRoute ) {
    console.log(route.pathFromRoot[1].snapshot.url[0].path);
}

If you go to, for example, http://localhost:4200/spreadsheet/3, the above code will log "spreadsheet"

import {Router} from '@angular/router'; // import Router from @angular/router

constructor(private router: Router){ // private member of Router
 const currentPageUrl = router.url; // router.url contain the active route info
 console.log('Activated router is ' + currentPageUrl);
}

Although you should be able to get the route from the ActivatedRoute, there may be times you want to get the route from your bootstrapped component. In this case you can use angular's Location Service and call location.path() to get the requested route.

Use like this

<a actionLink='['/list',id]'>link</a>


    constructor( private _route: ActivatedRoute ){ 
    let id=this._route.snapshot.param['id'];
    }

You have to import the ActivatedRoute.

Related