Standalone components have made a lot of things simpler, and one of my favourite things is how it makes managing routes easier.
First, we have just normal routing with standalone components. We define some routes:
export const routes: Routes = [
{
path: 'home',
loadComponent: () => import('./home/home.component'),
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full',
},
];
and can just supply the standalone component directly to the route using loadComponent
rather than having to use a module:
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};
What is even cooler is when we want to handle routing for nested features within the application. Let’s say we have an auth
section of the application that has multiple different features/pages, with routes like:
/auth/login
/auth/register
We could just define those routes directly in the main routes, but it’s a bit
nicer to have the auth
feature manage its own routes. To achieve this in
a standalone world, all we have to do is create some more routes at
auth/auth.routes.ts
:
import { Route } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
export const AUTH_ROUTES: Route[] = [
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{
path: '',
redirectTo: 'login',
pathMatch: 'full',
},
];
and then we can supply those directly in our main routes file like this:
export const routes: Routes = [
{
path: 'auth',
loadChildren: () => import('./auth/auth.routes').then((m) => m.AUTH_ROUTES),
},
{
path: 'home',
loadComponent: () => import('./home/home.component'),
},
{
path: '',
redirectTo: 'auth',
pathMatch: 'full',
},
];
Again, no NgModules
required, and we can now neatly co-locate the routing for
the auth
features.