12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
13 : 08 : 54 : 35
Become a member
to unlock all features

    Create a redirect rule with the Angular router

    Juri StrumpflohnerJuri Strumpflohner

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.