CanActivate vs. CanActivateChild with component-less routes

Solution 1:

From the docs:

As we learned about guarding routes with CanActivate, we can also protect child routes with the CanActivateChild guard. The CanActivateChild guard works similarly to the CanActivate guard, but the difference is its run before each child route is activated. We protected our admin feature module from unauthorized access, but we could also protect child routes within our feature module.

Here's a practical example:

  1. navigating to /admin
  2. canActivate is checked
  3. You navigate between the children of /admin route, but canActivate isn't called because it protects /admin
  4. canActivateChild is called whenever changing between children of the route its defined on.

I hope this helps you, if still unclear, you can check specific functionality by adding guards debugging them.

Solution 2:

In real world, I feel it is redundant to use the same guard for the parent and all its children.

For a better example, suppose you have roles for admin users (Edit/View), you can add a guard for "Edit" only tabs.

    RouterModule.forChild([
      {
        path: 'admin',
        component: AdminComponent,
        canActivate: [AuthGuard],  //1 - redirect to login page if not logged in
        children: [
          //View Access
          {
            ......
          },
          //Edit Access
          {
            path: '',
            canActivateChild: [EditGuard], //2 - display "you don't have Edit permission to access this page"
            children: [
              { path: 'crises', component: ManageCrisesComponent },
              { path: 'heroes', component: ManageHeroesComponent },
              { path: '', component: AdminDashboardComponent }
            ]
          }
        ]
      }
    ])