Angular Routing


What is routing in Angular?

Routing in Angular is the process of navigating between different views or pages in a single-page application (SPA). Angular's router allows developers to define navigation paths and map them to components, enabling dynamic and seamless transitions between views without reloading the entire page. The RouterModule provides directives and services to implement routing in Angular applications.


How do you set up basic routing in Angular?

To set up basic routing in Angular, you need to follow these steps:

  1. Import RouterModule and Routes from @angular/router in your app module.
  2. Define an array of route objects where each route maps a path to a component.
  3. Use the <router-outlet> directive in the main component to act as a placeholder for the routed components.
  4. Use routerLink for navigation.

Example of basic routing setup:

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 {}
<nav>
  <a routerLink="/">Home</a>
  <a routerLink="/about">About</a>
</nav>

<router-outlet></router-outlet>

In this example, routes are defined for the HomeComponent and AboutComponent, and the <router-outlet> serves as the placeholder where the routed components are displayed.


What is routerLink in Angular, and how is it used?

routerLink is a directive in Angular that enables navigation between routes. It binds the link to a route, and when the link is clicked, Angular's router navigates to the corresponding route without reloading the page.

Example of using routerLink:

<nav>
  <a routerLink="/">Home</a>
  <a routerLink="/about">About</a>
</nav>

In this example, the routerLink directive binds the <a> elements to the home and about routes, enabling navigation to those pages.


What is <router-outlet>, and how is it used?

<router-outlet> is a directive in Angular that acts as a placeholder for dynamically loading components based on the current route. When the route changes, Angular dynamically renders the corresponding component inside the <router-outlet> element.

Example of using <router-outlet>:

<router-outlet></router-outlet>

In this example, the <router-outlet> is where Angular will insert the routed components depending on the active route.


How do you create child routes in Angular?

Child routes in Angular allow you to create nested routes, where a route has its own set of sub-routes. This is useful for creating layouts with multiple levels of navigation.

Example of child routes:

const routes: Routes = [
  { path: 'products', component: ProductsComponent, children: [
    { path: 'details/:id', component: ProductDetailsComponent }
  ]}
];

In this example, the ProductsComponent has a child route details/:id that loads the ProductDetailsComponent. This allows navigation to a product's detail page under the /products route.


How do you pass parameters to routes in Angular?

You can pass route parameters in Angular by defining a route with a parameter in the path using the colon syntax (e.g., path: 'details/:id'). You can then access the parameter in the component using Angular's ActivatedRoute service.

Example of passing route parameters:

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

export class ProductDetailsComponent {
  productId: string;

  constructor(private route: ActivatedRoute) {
    this.productId = this.route.snapshot.paramMap.get('id');
  }
}
const routes: Routes = [
  { path: 'product/:id', component: ProductDetailsComponent }
];

In this example, the :id parameter is passed through the URL, and the ActivatedRoute service is used to retrieve it in the ProductDetailsComponent.


What is lazy loading in Angular routing?

Lazy loading in Angular is a technique used to load feature modules only when they are needed, improving application performance. Instead of loading all modules at startup, lazy-loaded modules are fetched and loaded when the user navigates to the specific route that requires the module.

Example of setting up lazy loading:

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

In this example, the AdminModule is lazy-loaded only when the user navigates to the /admin route, reducing the initial bundle size of the application.


What is route guard in Angular, and how is it used?

A route guard in Angular is a service that controls whether a route can be activated or deactivated based on certain conditions. Route guards are used to protect routes from unauthorized access, ensuring that only authorized users can access certain parts of the application.

Types of route guards include:

  • CanActivate: Decides if a route can be navigated to.
  • CanDeactivate: Decides if a route can be navigated away from.
  • CanActivateChild: Guards child routes.
  • CanLoad: Decides if a module can be loaded lazily.

Example of a route guard:

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return !!localStorage.getItem('token'); // Allow navigation if token exists
  }
}

In the routes definition:

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];

In this example, the AuthGuard is used to protect the dashboard route, only allowing access if the user has a valid token.


What is the difference between navigate and routerLink in Angular?

The routerLink directive is used in templates to bind a route to a clickable link, while the navigate method of the Router service is used programmatically in the component class to navigate to a route.

  • routerLink: Used for declarative navigation in templates.
  • navigate: Used for imperative navigation in the component class.

Example of using navigate in the component class:

import { Router } from '@angular/router';

export class ExampleComponent {
  constructor(private router: Router) {}

  goToAbout() {
    this.router.navigate(['/about']);
  }
}

In this example, the navigate method is used to navigate to the /about route programmatically when a method is triggered.


What is the purpose of pathMatch in Angular routes?

The pathMatch property in Angular routes determines how the router matches the URL with the defined path. It can have two values:

  • full: The path must match the URL exactly. This is usually used for the default route (e.g., path: '').
  • prefix: The path can match a prefix of the URL. This is used for routes that start with a common prefix.

Example of pathMatch:

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  { path: 'products', component: ProductsComponent }
];

In this example, the pathMatch: 'full' ensures that the empty path ('') matches only when the URL is exactly the base URL.


How do you implement a wildcard route in Angular?

A wildcard route in Angular is used to handle unknown or undefined routes. It typically redirects to a 404 error page or the home page if the route is not recognized. The wildcard route should always be the last route in the route configuration.

Example of a wildcard route:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '**', component: PageNotFoundComponent }
];

In this example, any unknown route will be handled by the PageNotFoundComponent.

Ads