Before we get into today’s topic: The Angular Team’s Request for Comments (RFC) for Angular Signals is now open to the public. Feel free to take a look and give your feedback.
Yesterday, we saw how to change an application’s title using the router config. Today, let’s cover more complex scenarios when we need a dynamic title set depending on other factors.
Using a resolver function
First, we might need some processing using a function to extract information from a service or API. In that case, we can use a resolver function that gets that data and returns it:
Note that the signature of that function allows us to return a string
, an Observable
, or a Promise
. That way, we can make an API request to fetch some extra data if needed. For instance, in the above example, getUsername() returns an Observable (code here). This is another excellent example of using the inject
function we covered earlier in this newsletter.
Using a title strategy service
For more complex scenarios, Angular allows us to create a custom TitleStrategy
. Such strategy takes the form of a service that has to implement an updateTitle
method:
Here is an example where I add a prefix to the title, then use the default title from the title property in the router config. Note that we could easily inject other services and perform async operations before setting the new title if needed:
Such title strategy service has to be provided as the default title strategy in our dependency injection configuration as follows:
You can see that example in action here on Stackblitz.