Routing in Angular: Learn Angular Part -3

Saurabh Pandey
6 min readMay 14, 2023

--

Routing plays an integral role in any Angular application. It allows us to define paths to different parts of our application, enabling users to navigate through different components or views. The following article will provide an in-depth look at Angular routing, complete with a practical example that incorporates a Bootstrap navbar.

Setting Up Angular Routing

First things first, when you’re generating a new Angular application, you can set up routing by providing the --routing flag:

ng new my-app --routing

This command generates a my-app project with a app-routing.module.ts file.

If you already have an application set up, you can manually generate the routing module:

ng generate module app-routing --flat --module=app

The --flat flag puts the file in src/app instead of its own folder, and --module=app tells the CLI to register it in the imports array of the AppModule.

Defining Routes

Routes are defined in an array of JavaScript objects, each object being a route. Each route object has a path and a component. The path is a string that corresponds to the URL, and the component is the component that will be displayed when the path is navigated to.

Let’s create three components: Home, Product, and Settings.

ng generate component home
ng generate component product
ng generate component settings

Now, define routes to these components in app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProductComponent } from './product/product.component';
import { SettingsComponent } from './settings/settings.component';

const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'product', component: ProductComponent },
{ path: 'settings', component: SettingsComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})

export class AppRoutingModule { }

The '' route redirects to the '/home' route because it's set to pathMatch: 'full'. This means, if the entire URL matches '' (i.e., if it's the default URL), then it will redirect to the 'home' route.

RouterOutlet

<router-outlet> is a directive provided by RouterModule, which acts as a placeholder for the component of the route that we navigate to.

In app.component.html, include <router-outlet>:

<router-outlet></router-outlet>

RouterLink

The routerLink directive is used for navigation between routes. Let's add a Bootstrap navbar with routerLink to our app.component.html:

First, ensure you’ve installed Bootstrap and added it to your angular.json file.

Then, update app.component.html:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">My App</a>
<div class="collapse navbar-collapse">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" routerLink="/home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/product">Product</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/settings">Settings</a>
</li>
</ul>
</div>
</div>
</nav>
<router-outlet></router-outlet>

This is a basic navbar setup using Bootstrap classes. The routerLink directive binds each link to the respective route. Clicking on a link triggers navigation to the corresponding route, whose component then gets loaded into the <router-outlet>.

Advanced Route Properties

Alongside path and component, there are other route properties you can use to customize your routes:

Let’s dive into each of these properties.

  • redirectTo: This property is used when you want to redirect from one route to another. For example:
{ path: '', redirectTo: '/home', pathMatch: 'full' }

In this case, if the entire URL path matches '' (i.e., if it's the default URL), then it will redirect to the 'home' route.

  • pathMatch: This property determines how the router should match the route with the URL. It can be 'full' or 'prefix'.
{ path: '', redirectTo: '/home', pathMatch: 'full' }

Here, 'full' means it should match the entire URL string. If it were 'prefix', it would match any URL that starts with the route's path.

  • children: This property is used for nested routes. For instance, you might have a 'user' route with child routes for 'profile' and 'settings':
{ 
path: 'user',
component: UserComponent,
children: [
{ path: 'profile', component: UserProfileComponent },
{ path: 'settings', component: UserSettingsComponent }
]
}
  • data: This property allows you to pass custom static data to a route. For example:
{ path: 'about', component: AboutComponent, data: { title: 'About Us' } }

You can access this data from within your component like so:

this.route.snapshot.data['title'];
  • resolve: This property is used for fetching data before navigating to a route. You need to implement a resolver service for this:
{ path: 'user/:id', component: UserComponent, resolve: { user: UserResolverService } }

Here, UserResolverService should implement the Resolve interface and fetch the data for the specific user. The fetched data can then be accessed in UserComponent similar to the data property.

  • canActivate: This property is used for protecting routes from unauthorized access:
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuardService] }

In this example, AuthGuardService is a service that implements the CanActivate interface. If the canActivate method in AuthGuardService returns false, navigation to the 'admin' route will be cancelled.

  • canDeactivate: Similar to canActivate, this property is used to prevent navigation away from the current route:
{ path: 'edit', component: EditComponent, canDeactivate: [CanDeactivateGuardService] }

In this case, CanDeactivateGuardService is a service that implements the CanDeactivate interface. If the canDeactivate method returns false, navigation away from the 'edit' route will be cancelled.

By leveraging these properties, you can create complex routing configurations that handle a variety of routing scenarios in your Angular application.

Conclusion

Routing is a powerful feature in Angular that allows us to create Single Page Applications (SPAs) where different views are loaded dynamically based on the URL. By understanding how to define and navigate routes, how to use the router-outlet directive, and how to leverage advanced route properties, you can create robust navigational structures for your Angular applications.

Resources

There are many resources available online where you can learn Angular, ranging from official documentation to online courses and books. Here are a few recommended ones:

  1. Official Angular Documentation: This should be your first stop when learning Angular. It’s comprehensive, well-organized, and kept up-to-date by the Angular team. It covers everything from the basics to more advanced topics. Link
  2. Angular University: A website dedicated to Angular topics. It includes a blog with many free resources and a number of paid courses. Link
  3. Udemy: There are many high-quality Angular courses on Udemy, such as “Angular — The Complete Guide” by Maximilian Schwarzmüller. Please note that while Udemy often has sales, its courses are not always free. Link
  4. Pluralsight: This platform offers a path specifically for Angular which includes a series of courses that cover Angular in depth. It’s a paid resource, but it does offer a 10-day free trial. Link
  5. Codecademy: Codecademy offers an interactive course on Angular, which is great for beginners. It’s a paid resource but does offer a limited free trial. Link
  6. Coursera: Offers a course called “Single Page Web Applications with AngularJS” from Johns Hopkins University. Coursera offers a 7-day free trial. Link
  7. Angular In Depth: A Medium publication that’s community-driven and features articles written by Angular experts. Link
  8. Stack Overflow: While not a learning resource in the traditional sense, Stack Overflow is a very useful platform for getting answers to specific questions you may have while learning or working with Angular. Link
  9. Youtube: There are many YouTube channels that offer free Angular tutorials. Some popular ones include Traversy Media, Academind, and The Net Ninja.
  10. ng-book: This is an in-depth book on Angular that covers a lot of ground. It’s updated regularly to include the latest versions of Angular. Link

Remember, the best way to learn is by doing. As you go through these resources, make sure to work on projects to apply what you’ve learned.

About the Author

Author Name: Saurabh Pandey

Saurabh Pandey is a passionate Software Engineer from India. With years of experience in the industry, Saurabh has honed his skills in various programming languages and technologies, allowing him to effectively lead and contribute to complex projects.

To connect with Saurabh and learn more about his work, you can visit his LinkedIn profile at https://www.linkedin.com/in/dextrop/.

--

--

No responses yet