DEV Community

Cover image for Angular Routing Crash Course
Eldrige
Eldrige

Posted on

Angular Routing Crash Course

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.
Alt Text
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.
Alt Text
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
Alt Text
4) Go to the app-routing.module file, inside it, you will find a routes array. This array will contain our route definitions

app-routing.module.ts - house-renting-app - Visual Studio Code 11_5_2020 12_49_20 AM
5) Insert the following code into the routes array, and also import each respective component.

app-routing.module.ts - house-renting-app - Visual Studio Code 11_5_2020 9_21_43 AM

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.

app.component.html - house-renting-app - Visual Studio Code 11_5_2020 11_29_05 AM

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.

HouseRentingApp - Mozilla Firefox 11_5_2020 2_10_50 PM

HouseRentingApp - Mozilla Firefox 11_5_2020 2_11_07 PM

๐ŸŽŠ๐ŸŽ‰๐ŸพCongratulations !!! You just learned the basics of routing in Angular. There is much more to routing in angular.

Top comments (0)