Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 74 ยท Projects

Project: Blog with Routing and Lazy Routes

Build an Angular blog with routes, a resolver that loads each post, a lazy blog area, pagination through query params and per-page titles and meta tags. Includes a runnable mini router.

A blog is a routing workout. Every post has its own URL, the list has pages, a missing post must lead to a friendly "not found" page, and each page needs its own title and description so search engines and people sharing links see something meaningful. These are exactly the things the Angular router is designed for.

In this project we plan the routes, load each post with a resolver, split the blog into a lazy feature area, store pagination in query parameters, and set the title and meta tags per page. The building blocks come from Routing Basics, Route Parameters, Query Params and Navigation, Child Routes and Lazy Loading and Guards, Resolvers and Router Events.

Real versus stand-in. The typescript and html blocks are real Angular code and read-only, because this site cannot run the Angular compiler or router. The runnable examples are stand-ins: a mini router that matches paths, lazy-loads child routes and runs resolvers, and a pagination helper that parses query strings the way the real components would. They teach the mechanism and print deterministic output.

The plan

The URL structure comes first, because it is a promise to your readers: addresses should stay stable and readable.

URL What it shows Loaded
/blog The post list, page 1 lazy blog area
/blog?page=2&tag=routing The list, page 2 of a tag lazy blog area
/blog/intro-to-signals One post lazy blog area, resolver
/about A static page own lazy chunk
/not-found Friendly 404 own lazy chunk
flowchart TD
  Root["app routes"] --> Blog["'blog' (loadChildren)"]
  Root --> About["'about' (loadComponent)"]
  Root --> NF["'not-found'"]
  Root --> Wild["'**' redirect to not-found"]
  Blog --> List["'' PostList<br/>(query params)"]
  Blog --> Post["':slug' PostDetail<br/>(resolver)"]

Two route tables: the root table and the blog table, which the browser downloads only when the user first visits /blog.

Step 1: the route tables

The root table lists the top-level areas. Only blog uses loadChildren, which loads a whole child route table on demand:

TypeScript
// app.routes.ts
import { Routes } from '@angular/router';

export const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'blog' },
  {
    path: 'blog',
    loadChildren: () => import('./blog/blog.routes').then(m => m.BLOG_ROUTES),
  },
  {
    path: 'about',
    title: 'About this blog',
    loadComponent: () => import('./about').then(m => m.About),
  },
  {
    path: 'not-found',
    title: 'Page not found',
    loadComponent: () => import('./not-found').then(m => m.NotFound),
  },
  { path: '**', redirectTo: 'not-found' },
];

The route table is ordered: the router takes the first match, so the ** wildcard must come last. The pathMatch: 'full' on the empty-path redirect matters, because without it every URL would "start with" the empty path and be redirected. The title property sets the document title when that route is active.

The blog area has its own table:

TypeScript
// blog/blog.routes.ts
import { Routes } from '@angular/router';
import { postResolver } from './post.resolver';

export const BLOG_ROUTES: Routes = [
  {
    path: '',
    title: 'Blog',
    loadComponent: () => import('./post-list').then(m => m.PostList),
  },
  {
    path: ':slug',
    resolve: { post: postResolver },
    loadComponent: () => import('./post-detail').then(m => m.PostDetail),
  },
];

Everything in this file, and the components it imports, ends up in a separate JavaScript chunk. A visitor who only reads /about never downloads it. To make later navigation feel instant you can add withPreloading(PreloadAllModules) to provideRouter(), which downloads lazy chunks in the background after the first page has loaded.

Step 2: a resolver that loads the post

A resolver runs before the route activates. It fetches the post, and the router shows the page only when the data is there, so the component never has to render a half-empty state. If the post does not exist, the resolver sends the user to the 404 page instead.

TypeScript
// blog/post.resolver.ts
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';
import { catchError, of } from 'rxjs';
import { Post, PostService } from './post.service';

export const postResolver: ResolveFn<Post> = route => {
  const posts = inject(PostService);
  const router = inject(Router);
  const slug = route.paramMap.get('slug') ?? '';

  return posts.bySlug(slug).pipe(
    catchError(() => of(new RedirectCommand(router.parseUrl('/not-found')))),
  );
};

A resolver is just a function that can call inject(). Returning a RedirectCommand makes the router navigate elsewhere instead of activating the route. With withComponentInputBinding() enabled in provideRouter(), the resolved value is passed straight into a component input with the same name, post, so the component needs no ActivatedRoute:

TypeScript
// blog/post-detail.ts
import { Component, effect, inject, input } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { RouterLink } from '@angular/router';
import { Post } from './post.service';

@Component({
  selector: 'app-post-detail',
  imports: [RouterLink],
  templateUrl: './post-detail.html',
})
export class PostDetail {
  readonly post = input.required<Post>();

  private readonly title = inject(Title);
  private readonly meta = inject(Meta);

  constructor() {
    effect(() => {
      const post = this.post();
      this.title.setTitle(`${post.title} | My Blog`);
      this.meta.updateTag({ name: 'description', content: post.summary });
    });
  }
}
HTML
<!-- blog/post-detail.html -->
<article>
  <h1>{{ post().title }}</h1>
  <p class="byline">{{ post().tag }}</p>
  <div [innerHTML]="post().html"></div>
  <a routerLink="/blog">Back to all posts</a>
</article>

Title and Meta from @angular/platform-browser change the document title and the meta description. They run in an effect(), so the tags update whenever the input changes, for instance when you move from one post straight to another and Angular reuses the component. The [innerHTML] binding is sanitized by Angular, which strips dangerous markup; do not bypass that with bypassSecurityTrustHtml for content you do not fully control (Security and Accessibility).

Step 3: pagination with query parameters

Where should the current page live? Not in a component field: a reload would lose it and nobody could share "page 3". It belongs in the URL, as a query parameter. With input binding, query parameters also arrive as component inputs.

TypeScript
// blog/post-list.ts
import { Component, computed, inject, input, numberAttribute } from '@angular/core';
import { RouterLink } from '@angular/router';
import { PostService } from './post.service';

const PAGE_SIZE = 5;

@Component({
  selector: 'app-post-list',
  imports: [RouterLink],
  templateUrl: './post-list.html',
})
export class PostList {
  private readonly posts = inject(PostService);

  readonly page = input(1, { transform: numberAttribute });
  readonly tag = input<string | undefined>(undefined);

  private readonly filtered = computed(() => {
    const tag = this.tag();
    const all = this.posts.all();
    return tag ? all.filter(post => post.tag === tag) : all;
  });

  protected readonly pageCount = computed(() =>
    Math.max(1, Math.ceil(this.filtered().length / PAGE_SIZE)),
  );

  protected readonly currentPage = computed(() =>
    Math.min(Math.max(1, this.page()), this.pageCount()),
  );

  protected readonly visible = computed(() => {
    const start = (this.currentPage() - 1) * PAGE_SIZE;
    return this.filtered().slice(start, start + PAGE_SIZE);
  });
}

Query parameters are strings, and users can type anything, so numberAttribute converts with a fallback and the currentPage computed clamps the value into a valid range. ?page=abc shows page 1 and ?page=999 shows the last page instead of an empty screen.

HTML
<!-- blog/post-list.html -->
@for (post of visible(); track post.slug) {
  <article>
    <h2><a [routerLink]="['/blog', post.slug]">{{ post.title }}</a></h2>
    <p>{{ post.summary }}</p>
  </article>
} @empty {
  <p>No posts found.</p>
}

<nav aria-label="Pagination">
  @if (currentPage() > 1) {
    <a [routerLink]="[]" [queryParams]="{ page: currentPage() - 1 }" queryParamsHandling="merge">Newer</a>
  }
  <span>Page {{ currentPage() }} of {{ pageCount() }}</span>
  @if (currentPage() < pageCount()) {
    <a [routerLink]="[]" [queryParams]="{ page: currentPage() + 1 }" queryParamsHandling="merge">Older</a>
  }
</nav>

[routerLink]="[]" means "stay on this route", and queryParamsHandling="merge" keeps the other parameters (here tag) while changing page. Because these are real links, readers can open them in new tabs and search engines can follow them. That is better than buttons with click handlers.

The first runnable example is the pagination logic and the per-page title and description, as pure functions, so you can see how the clamping and the SEO text behave for different query strings.

TypeScript Pagination from a query string, with titles and meta text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The clamping rules show up directly: page=abc falls back to page 1, page=99 becomes the last page, and an unknown tag gives an empty list with a single page. The "newer" link of page 2 is /blog, not /blog?page=1, so each list has exactly one address, which avoids duplicate content for search engines. The same link helper keeps the tag parameter, just like queryParamsHandling="merge".

Step 4: titles, meta tags and search engines

Three layers set the page title, from simple to flexible:

  1. A static title on the route, for pages like "About".
  2. A custom TitleStrategy, a class provided once that can add a suffix such as | My Blog to every title.
  3. Title and Meta services inside a component, for titles that depend on data, like each post.

Search engines and link-preview bots work best when the HTML they download already contains the right title and description. A client-side-only app serves the same empty HTML shell for every URL, so for a public blog you should add server-side rendering or prerendering, covered in SSR, Hydration and Prerendering. The Title and Meta calls in this project work unchanged in that setup.

Step 5: see the router work

The second runnable example is a mini router. It matches path segments, captures :slug, downloads the child table of loadChildren only once, runs resolvers before showing the page, and redirects when nothing matches or a resolver fails. Real Angular is far more capable (outlets, guards, relative links, matching strategies); this is the core idea.

TypeScript A mini router with lazy children, resolvers and redirects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Follow the output. The empty path redirects to /blog, and the first visit prints the "downloading the blog chunk" line exactly once; later blog URLs reuse the loaded table. The post title comes from resolved data. An unknown slug makes the resolver fail and the user lands on the not-found page, and a random path falls through to the ** route.

Ideas to extend it

  • Add a canDeactivate guard to a comment form that warns about unsaved text.
  • Show a loading bar from router events while a resolver runs (Guards, Resolvers and Router Events).
  • Add a sitemap.xml generated at build time from the list of posts.
  • Add related posts and tags as links, so readers move through the blog without going back to the list.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does loadChildren give a blog feature area?

    loadChildren points at a dynamic import. The bundler splits that code into its own file and the router downloads it on the first visit to the area.
  2. 2. Why does the empty-path redirect need pathMatch full?

    By default a path matches as a prefix, and the empty path is a prefix of everything. pathMatch full requires the whole remaining URL to be empty.
  3. 3. What is a good reason to keep the current page number in a query parameter?

    State that defines what the user sees belongs in the URL. A component field would be lost on reload and could not be linked to.
  4. 4. How should the page component treat page=abc or page=999 typed by a user?

    Query parameters are user input. Converting with a fallback and clamping keeps the page sensible whatever is typed.
  5. 5. Why should a public blog consider server-side rendering or prerendering?

    A client-only app sends the same empty shell for every URL. With SSR or prerendering each URL's HTML contains its own content and meta tags.

Summary

  • Design the URL structure first; keep addresses stable and readable, with a wildcard route last.
  • Use loadChildren for a lazy feature area and loadComponent for lazy single pages; preloading can download chunks in the background.
  • A resolver loads data before activation and can return a RedirectCommand for missing content; with withComponentInputBinding() the data arrives as an input.
  • Keep pagination and filters in query parameters, convert them safely, clamp them, and link with routerLink and queryParamsHandling="merge".
  • Set titles with route title, a TitleStrategy, or the Title and Meta services, and use SSR or prerendering for public pages.

Next: Project: Admin Dashboard with Auth.