Angular routing maps URLs to components, so users can navigate without full page reloads. 1. Define routes (standalone style, Angular 15+) // app.routes.ts export const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'products', component: ProductListComponent }, { path: 'products/:id', component: ProductDetailComponent }, { path: 'admin', canActivate: [authGuard], loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES) // lazy loaded }, { path: '**', component: NotFoundComponent } // wildcard, must be last ]; // main.ts bootstrapApplication(AppComponent, { providers: [provideRouter(routes, withComponentInputBinding())] }); In module-based apps the equivalent is RouterModule.forRoot(routes) in AppModule and RouterModule.forChild(...) in feature modules. 2. Display routed components Put <router-outlet></router-outlet> in the layout template. 3. Navigate - In templates: <a routerLink="/products" routerLinkActive="active">Products</a> - In code: this.router.navigate(['/products', id], { queryParams: { tab: 'reviews' } }); 4. Read parameters - inject(ActivatedRoute).paramMap (observable), or with withComponentInputBinding() simply declare an input: id = input<string>(); for the :id parameter. 5. Advanced features - Lazy loading with loadChildren or loadComponent to reduce the initial bundle. - Guards: canActivate, canMatch, canDeactivate (warn about unsaved changes), written as functions in modern Angular. - Resolvers to load data before activating a route. - Child routes for nested layouts, named outlets, redirects (redirectTo with pathMatch: 'full'). - Preloading strategies (PreloadAllModules or custom) to fetch lazy routes in the background. - Scroll position restoration and title strategies. Remember that route guards are a UX feature: the backend must still enforce authorization for every API call.
Ravindra Wadile · · 0 likes