#Implementing Conditional Component Rendering based on Guard

8 messages · Page 1 of 1 (latest)

knotty forge
#

Make two routes with canMatch:

function hasPermissionForA(): boolean {
  // whatever
}

export const routes: Routes = [
  {
    path: 'home',
    component: AComponent,
    canMatch: [hasPermissionForA]
  },
  {
    path: 'home',
    component: BComponent,
    canMatch: [hasPermissionForB]
  },
  {
    path: 'home',
    component: FallbackComponent,
  },
];
candid fjord
#
const routes: Routes = [
  {
    path: 'home',
    component: Test1Component,
    canMatch: [hasPermissionForTest1Component()],
  },
  {
    path: 'home',
    component: Test2Component,
  },
  { path: 'information/:id', component: BikeInfoComponent },
  { path: 'bikes', component: BikeComponent },
];

function hasPermissionForTest1Component(): boolean {
  const shouldItMatch = false;
  console.log('does it match ? ', shouldItMatch);
  return shouldItMatch;
}

I just did an example using the canMatch but it seems to always render the first component no matter what the permission function returns, maybe I missed something here

knotty forge
#

canMatch was added in Angular 14.1. You're using Angular... 5? You should upgrade.

candid fjord
#

You are right I did not mind the version.. thank you

candid fjord
knotty forge
#

It should be canMatch: [hasPermissionForTest1Component],, not canMatch: [hasPermissionForTest1Component()],

#

you want canMatch to call your function, otherwise your passing a boolean as canMatch, which is not a function, so canMatch tries to fall back to it being an injection token. And you can't inject boolean