Angular Routing and Navigation allow building Single Page Applications (SPAs) by enabling navigation between views or components without reloading the page.
1. What is routing in Angular?
Answer: Routing in Angular allows navigation between different components and views within a Single Page Application (SPA). It enables users to access various parts of the application using URLs without refreshing the page.
Example:
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: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Steps to Implement:
- Define routes in the
Routesarray. - Import
RouterModuleand configure it with the routes usingRouterModule.forRoot(). - Use the
<router-outlet>directive in the main template.
2. How do you configure routes in Angular?
Answer: Routes are configured using the Routes array in Angular. Each route object contains path and component properties that define the route and the component to display.
Example:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'contact', component: ContactComponent }
];
Steps to Configure:
- Import
RouterModuleandRoutesfrom@angular/router. - Define routes in the
Routesarray. - Add
RouterModule.forRoot(routes)to theimportsarray of theAppModule.
3. What is the purpose of the <router-outlet> directive?
Answer: The <router-outlet> directive acts as a placeholder for dynamically rendering components based on the current route.
Example:
<router-outlet></router-outlet>
Steps to Use:
- Add
<router-outlet>to the main template. - Ensure routes are properly configured.
- Navigate to different routes to dynamically render components in the outlet.
4. How do you navigate between routes programmatically?
Answer: You can navigate between routes programmatically using the Router service in Angular.
Example:
import { Router } from '@angular/router';
constructor(private router: Router) {}
navigateToAbout() {
this.router.navigate(['/about']);
}
Steps to Implement:
- Import
Routerfrom@angular/router. - Inject the
Routerservice into the component. - Use the
navigatemethod to navigate to the desired route.
5. What are route parameters, and how are they used?
Answer: Route parameters allow passing dynamic data in the URL, which components can access for processing.
Example:
const routes: Routes = [
{ path: 'product/:id', component: ProductComponent }
];
// Accessing in the Component
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
const productId = this.route.snapshot.paramMap.get('id');
}
Steps to Use:
- Define the parameter in the route using
:paramName. - Use
ActivatedRouteto access the parameter value.
6. What is the difference between query parameters and route parameters?
Answer:
| Aspect | Route Parameters | Query Parameters |
|---|---|---|
| Syntax | /product/:id | /product?id=123 |
| Use | Identifies a specific resource | Provides additional information |
| Access | paramMap.get('id') | queryParamMap.get('id') |
| Example URL | /product/123 | /product?id=123 |
7. What is lazy loading in Angular, and how is it implemented?
Answer: Lazy loading loads feature modules only when they are needed, reducing the initial load time of the application.
Example:
const routes: Routes = [
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
];
Steps to Implement:
- Create a feature module.
- Use
loadChildrento configure lazy loading for the module. - Ensure the feature module has its own routing module.
8. What is the difference between forRoot and forChild in routing?
Answer:
| Aspect | forRoot | forChild |
|---|---|---|
| Purpose | Configures the root routing module | Configures child routing modules |
| Use Case | Used in AppRoutingModule | Used in feature modules |
| Provides | Router services | No additional services |
9. How do you implement route guards in Angular?
Answer: Route guards restrict or allow access to routes based on specific conditions.
Example:
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate(): boolean {
return this.authService.isLoggedIn();
}
}
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];
Steps to Implement:
- Create a guard using
ng generate guard. - Implement the
CanActivateinterface. - Add the guard to the route’s
canActivateproperty.
10. What is the difference between canActivate and canActivateChild?
Answer:
| Aspect | canActivate | canActivateChild |
|---|---|---|
| Purpose | Protects a route | Protects child routes |
| Application | Applies to the parent route | Applies to all child routes |
11. How do you preload modules in Angular?
Answer: Preloading modules loads lazy-loaded modules in the background to improve user experience.
Example:
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule]
})
export class AppRoutingModule {}
12. What is a wildcard route?
Answer: A wildcard route is used to handle undefined routes, typically displaying a “404 Page Not Found” component.
Example:
{ path: '**', component: PageNotFoundComponent }
13. How do you use query parameters in navigation?
Answer: Query parameters pass additional data during navigation.
Example:
this.router.navigate(['/products'], { queryParams: { category: 'electronics' } });
14. What are router events in Angular?
Answer: Router events allow tracking navigation lifecycle stages (e.g., start, end).
Example:
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
console.log('Navigation started');
}
});
15. How do you define child routes?
Answer: Child routes enable nested routing within parent components.
Example:
const routes: Routes = [
{ path: 'account', component: AccountComponent, children: [
{ path: 'settings', component: SettingsComponent },
{ path: 'profile', component: ProfileComponent }
]}
];