1. What is Routing in Angular?
Routing allows you to navigate between views (components) in your Angular application using the URL. It manages:
-
Browser navigation
-
Lazy loading of modules/components
-
Parameter passing via URLs
2. Basic Routing Setup
app.routes.ts
(Angular 15+ standalone routing)
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { provideRouter } from '@angular/router';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)],
});
3. Using RouterOutlet
app.component.html
html<h1>Angular 19 Routing</h1>
<router-outlet></router-outlet>
This acts as a placeholder where routed components will render.
4. Navigation with Links
html<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
Or programmatically:
ts
import { Router } from '@angular/router';
constructor(private router: Router) {}
goToAbout() {
this.router.navigate(['/about']);
}
5. Route Parameters
Define route with params:
ts{ path: 'user/:id', component: UserComponent }
Access it in UserComponent
:
ts
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
}
6. Lazy Loading with Standalone Components
Angular 15+ and Angular 19 make it easy to lazy load even standalone components:
ts
{
path: 'lazy',
loadComponent: () => import('./lazy/lazy.component').then(m => m.LazyComponent)
}
7. Route Guards (Optional)
Example for AuthGuard
:
ts{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard]
}
8. Wildcard and Redirects
ts
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
No comments:
Post a Comment