0

Hopefully someone could help I have a sidebar with a list of items and each list item has a routerlink and I am struggling how to get the id of the current selection so each list item has that id to pass on to the component.

The app starts with a list of items from the database and when I click on the row it takes me to the child object and in the url has the id so that part is working but I somehow need to get that id so all the items in my sidebar have access to that id but can't figure it out and thought this was going to be an easy part and left it to the end.

So I need somehow once the item is selected that all items in routerlink get access to it.

<a [routerLink]="['/addresses/', this.id]" >Addresses <a [routerLink]="['/reports/', this.id]" >Reports

Thank you

Denz
  • 13
  • 3

1 Answers1

0

According to this post you can subscribe to changes of the route inside the sidebar component.

Try the following:

constructor(private router: Router) {
    router.events.subscribe((routerEvent) => {
        if (routerEvent instanceof NavigationEnd) {
          console.log('current route:', routerEvent.url);
          // parse the id from the url here e.g. routerEvent.split('/')[2]
        }
    });
  }
Simon
  • 194
  • 13
  • Sorry not working @deprecated — Use an observer instead of a complete callback currently when I go over the sidebar items in the url it has underfined where id should be – Denz Oct 03 '21 at 12:34
  • As sidebar gets loaded first it is not getting the id from components its probable very basic its frustrating when you get stuck I created a workaround with click but the routerlinkactive doesn't work – Denz Oct 03 '21 at 13:19
  • Thanks for the hint. I updated the answer now and tested it locally, it should work now. Hope this helps. – Simon Oct 04 '21 at 10:07
  • Thank you so much for that it is working perfectly I used this to get the id this.id = this.router.url.split('/')[2]; – Denz Oct 04 '21 at 12:14
  • Great, I am glad I could help. Could you mark my answer as accepted? – Simon Oct 04 '21 at 12:18