angular routing single-page-application code-examples
0 likes

Angular Routing: Explained with Code


Angular Routing: Explained with Code

Angular's routing system allows for sophisticated navigation structures, enabling developers to build single-page applications with dynamic content loading based on URL paths. Here's a comprehensive explanation of Angular routing along with sample code.

1. Setting up Routing

To begin, you need to set up routing for your Angular project. When generating a new project via Angular CLI, you can add the --routing flag:

Copy Code
ng new my-app --routing

This command creates an AppRoutingModule and imports it into AppModule.

2. Configuring Routes

Routes are configured as an array of objects, each object representing a potential navigation route.

Here's a simple configuration:

Copy Code
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];
  • The redirectTo option in the first route configures a default route.
  • pathMatch: 'full' ensures the entire URL matches before redirecting.
  • The other routes are straightforward: if "/home" is in the URL, the HomeComponent will be displayed and so on.

3. Importing Routes into AppModule

Next, you need to import the RouterModule into your AppModule and configure it with the routes using RouterModule.forRoot():

Copy Code
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

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

4. Displaying Components with <router-outlet>

To display content based on the active route, place the <router-outlet></router-outlet> directive in your template, usually in app.component.html:

Copy Code
<nav>
  <a routerLink="/home">Home</a>
  <a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
  • routerLink is a directive that binds a clickable HTML element to a route.
  • <router-outlet> is a placeholder where the routed component will be displayed.

5. Route Parameters

Angular routing also supports dynamic segments in routes. For example, to view user profiles by ID:

Copy Code
const routes: Routes = [
  ...
  { path: 'user/:id', component: UserProfileComponent }
];

Then, in your component, you can access the id parameter:

Copy Code
import { ActivatedRoute } from '@angular/router';

export class UserProfileComponent implements OnInit {
  userId: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.userId = this.route.snapshot.paramMap.get('id');
  }
}

6. Lazy Loading

For larger applications, you might not want to load all modules at startup. Angular supports lazy loading of modules:

Copy Code
const routes: Routes = [
  ...
  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
];

This ensures the AdminModule and its components aren't loaded until the "/admin" route is activated.

Conclusion

Angular's routing system provides a powerful and flexible mechanism for managing navigation and content loading in single-page applications. Proper utilization of this system ensures efficient and user-friendly web applications. The above examples give a glimpse into its capabilities, but Angular's router offers even more advanced features such as guards, resolvers, and nested routes.

0 comments