2

I have a button on my navbar. When clicked, I want a different behavior depending on which URI the user is currently on.

Let's say that I have this URI localhost:8080/entity/{entityId} How can I get entity, the first part of the URI, as a string in Angular 5.

Wissam Goghrod
  • 327
  • 1
  • 5
  • 15

3 Answers3

4

Ok I found the answer from Angular's doc, you have to use the UrlSegment Angular class from @angular/router to parse the url in segments link to the relevant doc: https://angular.io/api/router/UrlSegment

const tree: UrlTree = router.parseUrl('/team;id=33');
const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
const s: UrlSegment[] = g.segments;
s[0].path; // returns 'team'
s[0].parameters; // returns {id: 33}
Wissam Goghrod
  • 327
  • 1
  • 5
  • 15
0

First you must to import ActivatedRoute from Angular =>

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

Next Inject activatedRoute in your Component constructor =>

constructor(private activatedRoute: ActivatedRoute) {}

Now you can access to your children's routes, this console log will output an array of childrens.

ngOnInit() {
 console.log(this.activatedRoute.routeConfig.children);
}

You can get a lot of info about your url with ActivatedRoute. https://angular.io/api/router/ActivatedRoute

0

You can split the current url on the basis of '/', it will convert the url into an array and you can get any part you want. See the code snippet below:

url =window.location.href;

console.log(this.url.split('/')[1]);
Faisal Mushtaq
  • 485
  • 4
  • 11