angulardynamicangular-routingpage-title

Dynamic route data in angular


I'd like to know if it's possible to dynamically change the current route's data (using angular 6)

I've got the following route config

 {
    path: 'collections', component: CollectionListComponent, data: {title: "List of collections"},
    children:
      [
        {
          path: ':collectionId', component: CollectionDetailsComponent, data: {title: "Collection details"},
        }
      ]
  } 

I've got a header component that listens to routing events and retrieves the data to display the title.

   this.router.events.pipe(
      filter(e => e instanceof NavigationEnd))
      .forEach(e => {
        if(e instanceof NavigationEnd)
        {

          let r = route.firstChild;
          while(r.firstChild)
          {
            r = r.firstChild;
          }
          this.title= r.snapshot.data['title'];
        }

      });

Now, instead of displaying a static title when I'm on the CollectionDetails component, I'd like to display a dynamic one, e.g. "Collection [collectionName] details".

Is it possible to achieve this using route data?

I know I can do it using a service that broadcasts the dynamic header, but I'd like to know if there is a better way.


Solution

  • You can use a resolver like described here: https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

    I created a stackblitz to show https://stackblitz.com/edit/angular-route-data

    When your application becomes bigger and you need to share more and more data between components I would recommmend using a state management library like ngrx or ngxs. I recently switched from ngrx to ngxs because it needs less boilerplate code