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
Published 7 years ago
Updated 8 months ago

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.

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today