1. 2
    Create a redirect rule with the Angular router
    1m 31s
⚠️ This lesson is retired and might contain outdated information.

Create a redirect rule with the Angular router

Share this video with your friends

Social Share Links

Send Tweet

A common use case is to redirect to some home view of your application, especially at the first visit of the user. In this lesson we are going to learn how to define a redirect with the Angular router.

In our simplification here, we have defined a couple of routes which we have registered to the RouterModule's forRoot method. If we refresh our application, we can see that none of our components gets actually shown.

They only get loaded if we navigate directly to the about route, or to the home route. What we would rather like to have is that whenever we come to the root of our application, it automatically redirects to our home route.

In order to achieve this, we can specify a redirect route. First of all, we define here the path, which will be the empty string, and then rather to define a component here, we can use the redirectTo property and specify home.

There's another thing we need to do here, which is to define a path matching strategy, which in this case will be full. The default is prefix. What prefix means is that Angular is going to analyze the route here and match it incrementally.

The problem is that whenever we have another route down below, it will never go and actually invoke that route, because every route starts with an empty string. Therefore, always this route here will be matched.

If we specify the full matching strategy, this means that this route will only be matched if the route is completely empty, so it matches 100 percent this definition here.

Now let's actually save this and test whether this works. Let's remove the route definition up there, and as you can see, it properly redirects now to our home route.