Angular Router & Navigation: Steering Through Single Page Applications
Angular Router & Navigation: Steering Through Single Page Applications
Angular provides a powerful router that enables navigation from one view to the next as users perform tasks in your Single Page Application (SPA). It allows for lazy loading of modules, detailed configuration of how routes are handled, and much more.
1. Basic Configuration:
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, 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 }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
2. Router Outlet and Links:
Use <router-outlet>
directive in your component templates to mark where the router should display the component views.
Use routerLink
to create navigation links:
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
<router-outlet></router-outlet>
3. Route Parameters:
Routes can have parameters, which are tokenized segments of the URL:
{ path: 'profile/:id', component: ProfileComponent }
In your component, use ActivatedRoute
to access the id
parameter:
constructor(private route: ActivatedRoute) {
const id = this.route.snapshot.paramMap.get('id');
}
4. Child Routes & Lazy Loading:
Child routes allow nesting of routes, and lazy loading allows loading parts of the app asynchronously.
Example of Lazy Loading:
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
5. Route Guards:
Angular provides route guards to decide if a route can be activated, loaded, or left:
CanActivate
CanActivateChild
CanLoad
CanDeactivate
6. Navigation Extras:
While navigating, you can pass additional options using NavigationExtras
:
this.router.navigate(['/home'], { queryParams: { session: '12345' }, fragment: 'section1' });
7. Handling Unknown Routes:
Handle them using a wildcard route:
{ path: '**', component: PageNotFoundComponent }
Conclusion:
Angular's router offers a comprehensive solution to handle navigation and routing in SPAs. By understanding its core concepts and features, developers can create efficient, navigable, and modular applications that provide seamless user experiences.