ProgrammingWeb Development

Angular Routing Guide: Lazy Loading, Guards and Resolvers

Routing decides which component the user sees for a given URL. In modern Angular (v17 and later) routes are configured with provideRouter, components are standalone, and guards and resolvers are plain functions. This guide walks through a complete setup: basic routes, parameters, lazy loading, guards, resolvers, and the options that are worth enabling.

Basic setup

Define the routes in their own file:

// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { NotFoundComponent } from './not-found/not-found.component';

export const routes: Routes = [
  { path: '', component: HomeComponent, title: 'Home' },
  { path: 'about', loadComponent: () => import('./about/about.component').then((m) => m.AboutComponent), title: 'About' },
  { path: '**', component: NotFoundComponent, title: 'Page not found' },
];

Register them when bootstrapping the app:

// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';

bootstrapApplication(AppComponent, {
  providers: [provideRouter(routes, withComponentInputBinding())],
});

And add a <router-outlet /> where routed components should render:

<nav>
  <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a>
  <a routerLink="/about" routerLinkActive="active">About</a>
</nav>
<router-outlet />

The title property sets document.title automatically, which is good for both users and SEO. The wildcard ** route must be last, because routes are matched in order.

Route parameters as inputs

With withComponentInputBinding(), path parameters, query parameters and resolved data are passed straight into component inputs. No need to inject ActivatedRoute and subscribe:

// { path: 'products/:id', loadComponent: ... }
export class ProductDetailComponent {
  id = input.required<string>();          // from :id
  tab = input<string>('overview');        // from ?tab=reviews

  private api = inject(ProductApi);
  product = toSignal(toObservable(this.id).pipe(switchMap((id) => this.api.get(id))));
}

Because id is a signal, navigating from /products/1 to /products/2 (which reuses the same component instance) updates the product automatically.

Navigating from code

private router = inject(Router);

openProduct(id: string) {
  this.router.navigate(['/products', id], { queryParams: { tab: 'reviews' } });
}

Prefer the array form over string concatenation; Angular encodes each segment for you.

Child routes and layouts

Child routes render inside a parent component’s own <router-outlet />, which is how you build shared layouts:

{
  path: 'account',
  loadComponent: () => import('./account/account-layout.component').then((m) => m.AccountLayoutComponent),
  children: [
    { path: '', redirectTo: 'profile', pathMatch: 'full' },
    { path: 'profile', loadComponent: () => import('./account/profile.component').then((m) => m.ProfileComponent) },
    { path: 'orders', loadComponent: () => import('./account/orders.component').then((m) => m.OrdersComponent) },
  ],
},

pathMatch: 'full' is required on empty-path redirects; without it, the redirect would match every child URL.

Lazy loading a whole feature

For larger features, lazy load a separate routes file with loadChildren:

// app.routes.ts
{ path: 'admin', loadChildren: () => import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES) },
// admin/admin.routes.ts
export const ADMIN_ROUTES: Routes = [
  { path: '', component: AdminDashboardComponent },
  { path: 'users', component: AdminUsersComponent },
];

The admin code is downloaded only when someone visits /admin. To load lazy chunks in the background after the app starts, add a preloading strategy:

provideRouter(routes, withComponentInputBinding(), withPreloading(PreloadAllModules));

Functional guards

Guards decide whether navigation may continue. They are plain functions that can use inject():

// auth.guard.ts
import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);

  return auth.isLoggedIn()
    ? true
    : router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};
{ path: 'account', canActivate: [authGuard], loadComponent: ... }

Returning a UrlTree instead of calling router.navigate() inside the guard lets the router cancel the current navigation cleanly and redirect.

Other guard types:

GuardRuns whenTypical use
canActivateBefore entering a routeAuthentication
canActivateChildBefore entering any child routeRole checks for a whole section
canMatchWhile matching routesServe different components for the same URL (e.g. admin vs user), or skip lazy loading entirely
canDeactivateBefore leaving a route“You have unsaved changes” prompts

A canDeactivate guard for unsaved forms:

export interface HasUnsavedChanges {
  hasUnsavedChanges(): boolean;
}

export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
  component.hasUnsavedChanges() ? confirm('Discard unsaved changes?') : true;

Resolvers

A resolver loads data before the route activates, so the component never renders in an empty state:

export const productResolver: ResolveFn<Product> = (route) =>
  inject(ProductApi).get(route.paramMap.get('id')!);
{ path: 'products/:id', resolve: { product: productResolver }, loadComponent: ... }

With input binding, the resolved value arrives as an input with the same key:

export class ProductDetailComponent {
  product = input.required<Product>();
}

Use resolvers for small, essential data. For slow requests, it is usually better to navigate immediately and show a skeleton, because a resolver blocks the whole navigation until it completes.

Handling scroll position

By default Angular keeps the scroll position when you navigate, which feels wrong on content sites. Enable scroll restoration:

provideRouter(
  routes,
  withComponentInputBinding(),
  withInMemoryScrolling({ scrollPositionRestoration: 'enabled', anchorScrolling: 'enabled' }),
);

New pages now start at the top, the back button restores the previous position, and links like /docs#install scroll to the anchor.

Common mistakes

  1. Putting the ** wildcard route before other routes. Everything after it becomes unreachable.
  2. Forgetting pathMatch: 'full' on redirectTo: '' routes.
  3. Subscribing to ActivatedRoute.params and forgetting that the component instance is reused between parameter changes. Use input binding or switchMap.
  4. Navigating inside guards with router.navigate() instead of returning a UrlTree.
  5. Using heavy resolvers that make the app feel slow. Resolve only what the page cannot render without.
  6. Using relative links (routerLink="edit") without realising they resolve relative to the current route. Use / for absolute paths when in doubt.

Summary

A solid Angular routing setup today looks like this: provideRouter with withComponentInputBinding(), lazy loadComponent/loadChildren for anything that is not on the first screen, functional guards returning UrlTrees, small resolvers for essential data, route titles, and scroll restoration enabled.

Ahmet Rahmi Dokumacı

Software developer based in Istanbul, building products at FavolaSoft (favolasoft.com). I work with .NET, Angular, SQL Server and PostgreSQL and write about the problems I solve in real projects.

Related Articles

Leave a Reply

Back to top button