How to implement routing in Angular ?

 Implementing routing in Angular is a key feature that allows you to navigate between different views or components in a single-page application (SPA) without requiring a page reload. Routing in Angular is handled by the Angular Router, which helps manage the navigation and mapping of URLs to specific components.

Here’s a step-by-step guide to implement routing in Angular:


Step 1: Setting up a New Angular Project

First, ensure you have Angular CLI installed. If you haven’t installed it yet, you can do so by running:

bash

npm install -g @angular/cli

Create a new Angular project (if you don't have one already):

bash

ng new angular-routing-app cd angular-routing-app

During the project creation, make sure to choose Yes for the routing option when prompted.


Step 2: Create Components for Navigation

Next, create the components that you want to navigate between. For example, let's create three components: Home, About, and Contact.

Run the following commands to generate the components:

bash

ng generate component home ng generate component about ng generate component contact

This will create the HomeComponent, AboutComponent, and ContactComponent.


Step 3: Define Routes

Routing is configured in Angular using the RouterModule. Routes define which component should be displayed when the user navigates to a specific path.

  1. Create a new file app-routing.module.ts (if not already created).

    Inside this file, define the routes and the components associated with them.

    typescript

    import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { ContactComponent } from './contact/contact.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, // Default route { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], // Configure the routes exports: [RouterModule] // Make RouterModule available throughout the app }) export class AppRoutingModule { }

In the code above:

  • path: '': This is the default route, which redirects the user to the /home route when they visit the root URL of the app.
  • path: 'home': This will show the HomeComponent when navigating to /home.
  • path: 'about': This will show the AboutComponent when navigating to /about.
  • path: 'contact': This will show the ContactComponent when navigating to /contact.

Step 4: Update app.module.ts

You need to import the AppRoutingModule in your main module (app.module.ts) to enable routing across your app.

In app.module.ts, add the following imports and declarations:

typescript

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { ContactComponent } from './contact/contact.component'; import { AppRoutingModule } from './app-routing.module'; // Import the routing module @NgModule({ declarations: [ AppComponent, HomeComponent, AboutComponent, ContactComponent ], imports: [ BrowserModule, AppRoutingModule // Add the routing module here ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

Step 5: Set Up Navigation in app.component.html

Now that you have your routes set up, you need to provide a way for users to navigate between the different components. This is typically done using links.

Open app.component.html and add the following navigation links:

html

<nav> <ul> <li><a routerLink="/home">Home</a></li> <li><a routerLink="/about">About</a></li> <li><a routerLink="/contact">Contact</a></li> </ul> </nav> <!-- This is where the routed components will be displayed --> <router-outlet></router-outlet>
  • routerLink: This directive is used to navigate to a route when clicked.
  • router-outlet: This is the placeholder where Angular will dynamically display the component associated with the active route.

Step 6: Define Component Templates

Add some content to each component’s template to differentiate them:

  1. Home Component (home.component.html):

    html

    <h1>Welcome to the Home Page</h1> <p>This is the Home component.</p>
  2. About Component (about.component.html):

    html

    <h1>About Us</h1> <p>This is the About component.</p>
  3. Contact Component (contact.component.html):

    html

    <h1>Contact Us</h1> <p>This is the Contact component.</p>

Step 7: Run the Application

Now, run your application:

bash

ng serve

Go to http://localhost:4200 in your browser. You should see the home page with navigation links to Home, About, and Contact. When you click on the links, Angular will update the content dynamically without a page reload.

Additional Routing Features in Angular:

  • Route Parameters: You can pass dynamic parameters in the route path (e.g., product/:id) and retrieve them in the component.

    Example:

    typescript

    { path: 'product/:id', component: ProductDetailComponent }

    You can access the parameter in the component with ActivatedRoute:

    typescript

    import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) { this.route.params.subscribe(params => { const productId = params['id']; // Do something with productId }); }
  • Lazy Loading: For large applications, you can load modules and components only when they are needed using lazy loading. This helps to reduce the initial loading time of the app.

    To implement lazy loading, you need to configure the loadChildren property in your routing module:

    typescript

    const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', loadChildren: () => import('./about/about.module').then(m => m.AboutModule) }, { path: '', redirectTo: '/home', pathMatch: 'full' } ];
  • Route Guards: You can protect certain routes with Route Guards (e.g., to prevent unauthorized access). Guards can be used to check conditions before navigating to a route.


Conclusion

Implementing routing in Angular is simple and powerful, allowing you to build complex, dynamic SPAs with ease. The key steps are:

  1. Create Components for different views.
  2. Define Routes in a separate app-routing.module.ts file.
  3. Add Navigation Links in your templates using routerLink.
  4. Use <router-outlet> to display routed components dynamically.

With Angular's routing module, you can handle more advanced features like lazy loading, route parameters, and guards to build a scalable, maintainable application.

Comments

Popular posts from this blog

Is there a compatibility list for Angular / Angular-CLI and Node.js?

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

How to resolve CORS issue in Angular 12?