Angular – Routing

In the last tutorial, we showed how to create and use services. This time, we will discuss routing i.e. how to create and use routes.

Routing basically controls the flow of our application. It can direct which component would show or where it should be redirected. Let’s look at our basic running app.

routing

Previously, there’s a list of stocks that is shown below the header. Now, our goal here is when we put localhost:4200/stocks on the URL, it will redirect us to list of stocks.

First, we need to set our homepage. On your file explorer, click index.html.

routing

Next, let’s add the base href which is the file itself(index.html).

  • We just added the <base> tag under the head.

Now we are ready to create the routing file. In your file explorer under the src/app folder, create a new file and name it app.routing.ts.

routing

routing

Open the file and we’ll make a very basic routing class.

routing

  • Basically the variable ‘path’ sets the navigation of the route and ‘component’ controls which component to use if the route is called.

Next, go to your app.component.html file. In here we will use our router link.

This will show us the list of stocks we defined by clicking the word ‘STOCKS’. Save your work and go back to your browser (provided it is still running via the command ‘ng serve’).

routing

Click the word ‘STOCKS’ and the router link should add the extension ‘/stocks’ in the URL.

routing

Congratulations! You’ve successfully created a router link.

On the next lesson, we will talk about Template Reference Variables.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.