So what is routing?
In web development routing, refers to splitting the application into different areas based on the URL, that is derived from the current browser.
Why do you need routing?
- To separate the app into different areas
- To keep our app in a clean state
- Protect areas of our app, based on certain rules
👩🍳 Recipe
1) Generate a new angular application using the CLI, passing the --routing flag.
The --routing flag sets up our routing module, and equally imports it to the app.module.
2) Open your newly created app, and navigate to app.component.html. Add the bottom of the file, you should see the router-outlet directive.
The router-outled directive displays our routed components
On top of the router-outlet directive, we will add a bootstrap navbar, to ease navigation. You can get it here
https://getbootstrap.com/docs/4.5/components/navbar/
3) Now go ahead and generate the following components using the CLI, home, about us, contact, not-found
4) Go to the app-routing.module file, inside it, you will find a routes array. This array will contain our route definitions
5) Insert the following code into the routes array, and also import each respective component.
The route array basically contains objects.
- The path defines what text should be added to the URL.
- The component defines which component should be displayed for that particular route.
- The path containing the empty string,'' defines the route, as the default route.
- The path containing '**', serves as a wildcard route, which is used to redirect the user to a defined component if the current URL is invalid.
6) Now, in the app.component.html we will remove the href attribute and replace it with the routerLink directive. We now map the routerLink directive to our defined paths.
Now, we can serve our application and test our various links.
Initially, we get routed to the HomeComponent, because we defined it, as the default path.
🎊🎉🍾Congratulations !!! You just learned the basics of routing in Angular. There is much more to routing in angular.
Top comments (0)