When building my website and blog, I wanted to use it as an opportunity to learn more about Angular's relatively new Static and Server side rendering.
During this journey of experimentation and discovery, I suddenly had a problem; How do I set a dynamic page's title? At the time of writing, Angular's own guides did not really address this, other than for static (non-parametered) routes, and most of the tutorials and AI advice I found focused on building a service to set the title.
After some digging into Angular's code documentation, I finally found the "correct" way to do it: A title resolver function.
Title Resolver Function
First, you need to create a resolver function. You can do this via Angular CLI ng g resolver [name]
, or since its so tiny, you can write it out:
import { ResolveFn } from '@angular/router';
import { FRONTMATTER_ROUTES } from '../../compiled-frontmatter-routes';
/**
* Generates (or 'resolves') a title string from router data
*
* In this case we prefix with a constant string "Blog Post - " and search an array for a matching item and use the title from that item
*/
export const blogPostPageTitleResolver: ResolveFn<string> = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
return 'Blog Post - ' + FRONTMATTER_ROUTES.find(item => item.id === route.params['id'])?.title;
};
The return from the resolver function should be the title as a string. You can inject services, make calls to external resources or
use predefined data, and use the router data, such as route parameters (e.g. route.params['id']
) to filter your data source.
The final step is to include the resolver function in the route definition title property:
// imports ...
import { blogPostPageTitleResolver } from './blog-post-page-title.resolver'; // <-- Import the resolver function (your IDE should do this, but just in case)
// ...
export const routes: Routes = [
// ...
{
path: 'blog/:id',
component: BlogPostPageComponent,
title: blogPostPageTitleResolver, // <-- Add the Resolver function call to the title property
},
// ...
];
// ...
Conclusion
You should now see in your web app, when you navigate to your route, the title now accurately reflects what you are looking at:
I think there are at least two takeaways here: Firstly, if it feels like there should be a nice solution, but it's not obvious or documented nicely, check the code references, there maybe a more elegant way hidden buried. Secondly, Angular is really powerful, but its lack of documentation might be why it lacks the popularity of other frameworks and front end libraries. I, for one, will definitely be contributing this feature to the official docs due to its criticality for SEO on SSR and Static generated websites (like this blog).
Next steps
If you're interested in Static and Server-side rendered websites using angular, consider looking into route resolvers and prerender parameters. Blog post on this subject is coming soon!