Angular 5+ breadcrumb

Bo Vandersteene
2 min readNov 13, 2017

--

Breadcrumbs are nice to have for your application. With angular, you can write it in only a few lines of code. Even with a layout that fits your housestyle , or a reusable component in your company.

From the route /forms/details we want to generate the following breadcrumb:

How we build it:

1. Create a type for the breadcrumb

As we all we like typescript, and want to avoid the any type, we create a definition of our breadcrumb

2. Listen to the router event

Each time the router changes from route, there are several events dispatched. But we only capture the NavigationEnd event. For this reason we do the filter. The distinctUntilChanged prevents us to do the things twice and finally we map it to a nice breadcrumb array structure.

We start to build our breadcrumbs with the root of the activated route (is the same as the route we are actual on).

3. Build the breadcrumb

The next step is the most important of all. Here we are able to build our breadcrumb.

We are able to capture certain data about our route.

  • The current path.
  • The data past to that path
  • The component available
  • Does the path has more children

More details on the ActivatedRoute and RouteConfig can be found on https://angular.io/api/router/ActivatedRoute

Each time we detect that there is still a child with `route.firstChild` we build our next breadcrumb item.

4. We still need to display the breadcrumb on the screen.

This part can be done in the template of our breadcrumb component. We only start to subscribe on the breadcrumb stream when we render it on the screen. For this we use the async pipe. Angular has a nice build in system for subscribing, unsubscribing, … . So make use of it and try to avoid subscribing by your own on streams.

Make your own css of it, it should look nice in your application, you can also add a bootstrap template or materialize design on top of it.

5. Let your routes know their label!

If your breadcrumb is available, you want this one has a nice label. Not just the path. This can be done in the routes file. You give a data parameter with the label of your breadcrumb.

6. So now it is up to you

Feel free to check out the gitlab repo I’ve made out of it. Make use of the easy way of adding breadcrumbs to your angular project!

--

--

Bo Vandersteene

Frontend Software Engineer & Mentor, works with Angular, Typescript, Javascript. Strong interreset in GIS