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.
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.
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.
Open the file and we’ll make a very basic routing class.
- 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’).
Click the word ‘STOCKS’ and the router link should add the extension ‘/stocks’ in the URL.
Congratulations! You’ve successfully created a router link.