Routing


Routing Interview with follow-up questions

1. What is routing in Angular?

Routing maps URLs to components, letting Angular swap views in place so a single-page app behaves like a multi-page one — deep-linkable URLs, working back/forward buttons, and no full page reload. It's provided by the Angular Router (@angular/router).

The mechanics to mention: you define a Routes array mapping pathcomponent (or a lazy loadComponent), register it, and place a `` where the matched component should render. Navigation happens declaratively via routerLink or programmatically via the Router service.

The current framing interviewers expect: modern apps register routes with provideRouter(routes) in bootstrapApplication (the standalone API), use loadComponent/loadChildren for lazy loading, functional guards for access control, and features like withComponentInputBinding() to bind route params straight to component inputs. The old RouterModule.forRoot() still works but is the legacy NgModule style.

↑ Back to top

Follow-up 1

How does routing help in creating Single Page Applications?

Routing helps in creating Single Page Applications by allowing us to load different components or views based on the URL. When a user navigates to a different URL, the router maps that URL to a specific component and loads it into the designated area of the page. This allows us to create a seamless user experience where only the necessary content is loaded and displayed, without the need for a full page refresh.

Follow-up 2

What is the role of the RouterModule?

The RouterModule is a built-in Angular module that provides the necessary functionality for routing in Angular. It provides the RouterModule.forRoot() method to configure the routes for the application, and the RouterModule.forChild() method to configure routes for feature modules. It also exports the RouterModule, which allows other modules to import and use the routing functionality.

Follow-up 3

Can you explain how the router outlet works in Angular?

The router outlet is a directive provided by the RouterModule that acts as a placeholder for the dynamically loaded components. It is used in the template of the parent component to define where the child components should be rendered. When a user navigates to a specific URL, the router outlet dynamically loads and renders the corresponding component into its position in the parent component's template. This allows the content to be updated based on the user's navigation without the need for a full page refresh.

2. How do you configure routes in Angular?

Define a Routes array and register it. In modern standalone Angular you use provideRouter in the app config rather than an NgModule:

// app.routes.ts
export const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'users/:id', component: UserComponent },
  { path: 'admin', loadChildren: () => import('./admin.routes').then(m => m.ADMIN_ROUTES) },
  { path: '**', component: NotFoundComponent },   // wildcard last
];

// main.ts
bootstrapApplication(AppComponent, {
  providers: [provideRouter(routes, withComponentInputBinding())],
});

Then add `to the template and importRouterLink` for navigation.

Points worth making: order matters — Angular takes the first match, so put the ** wildcard and redirectTo routes last; prefer loadComponent/loadChildren for lazy loading; and withComponentInputBinding() lets route params arrive as component inputs. The older RouterModule.forRoot(routes) inside an AppRoutingModule (as some guides still show) is the legacy NgModule approach — functional but no longer the default.

↑ Back to top

Follow-up 1

What is the significance of the path and component properties in the route configuration?

In the route configuration, the 'path' property specifies the URL path for the route, while the 'component' property specifies the component that should be displayed when the route is activated.

For example, in the following route configuration:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent }
];

The 'path' property defines the URL paths '/home', '/about', and '/contact', and the 'component' property specifies the corresponding components HomeComponent, AboutComponent, and ContactComponent. When a user navigates to '/home', the HomeComponent will be displayed.

Follow-up 2

How do you handle invalid URLs?

To handle invalid URLs in Angular, you can define a wildcard route that will be used when no other routes match the requested URL. This wildcard route can be used to display a custom 404 page or redirect the user to a default route.

Here's an example of how to handle invalid URLs:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
  { path: '**', component: NotFoundComponent }
];

In this example, the '**' path is a wildcard that will match any URL that doesn't match the previous routes. The NotFoundComponent will be displayed for invalid URLs.

Follow-up 3

Can you explain how to set up nested routes?

In Angular, you can set up nested routes by defining child routes within a parent route. This allows you to create a hierarchical structure for your routes.

Here's an example of how to set up nested routes:

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

In this example, the 'products' route is the parent route, and it has two child routes: 'list' and 'details/:id'. The 'list' route is mapped to the ProductListComponent, and the 'details/:id' route is mapped to the ProductDetailsComponent. When a user navigates to '/products/list', the ProductListComponent will be displayed, and when a user navigates to '/products/details/123', the ProductDetailsComponent will be displayed with the corresponding product ID.

3. What are route parameters and how are they used in Angular?

Route parameters are dynamic segments of a URL, declared with a colon in the path (users/:id), used to pass identifying data to a component — e.g. which user to show.

You read them from ActivatedRoute. Because a component instance can be reused as the param changes, subscribe to the observable rather than reading once:

private route = inject(ActivatedRoute);
id$ = this.route.paramMap.pipe(map(p => p.get('id')));
// or signals: id = toSignal(this.route.paramMap).get('id')

Distinctions interviewers like: route params (/:id, required, part of the path) vs query params (?sort=asc, optional, via queryParamMap) vs data (static) and resolvers (preloaded data). The modern shortcut worth naming: with withComponentInputBinding(), Angular binds route params directly to matching @Input()/input() properties, so you often don't need ActivatedRoute at all — id = input.required() just receives it.

↑ Back to top

Follow-up 1

How do you retrieve parameters from a route?

To retrieve parameters from a route, you can use the ActivatedRoute service provided by Angular. The ActivatedRoute service has a params property that is an Observable. You can subscribe to this Observable to get the current route parameters. Here is an example:

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

@Component({
  // ...
})
export class MyComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.params.subscribe(params => {
      // Access the route parameters
      const id = params['id'];
      const name = params['name'];
      // ...
    });
  }
}

Follow-up 2

What is the difference between required and optional route parameters?

Required route parameters are defined with a colon (:) in the route configuration and must be provided in the URL for the route to match. Optional route parameters are defined with a question mark (?) in the route configuration and can be omitted from the URL. If an optional route parameter is not provided, the corresponding parameter in the component will be undefined.

Follow-up 3

Can you explain how to use matrix parameters?

Matrix parameters are a way to pass additional data to a route. They are similar to query parameters, but are embedded in the URL path instead of being appended to the URL. To use matrix parameters, you need to define them in the route configuration using a semicolon (;) followed by the parameter name. Here is an example:

const routes: Routes = [
  { path: 'product/:id;version=:version', component: ProductComponent }
];

In the above example, the route has a matrix parameter named 'version'. To access the matrix parameter in the component, you can use the ActivatedRoute service in the same way as for route parameters.

4. What is route guard in Angular?

A route guard is a function the Router runs to decide whether navigation can proceed — typically for auth, permissions, or preventing data loss. The guard types:

  • CanActivate / CanActivateChild — allow entering a route / its children.
  • CanDeactivate — allow leaving (e.g. "discard unsaved changes?").
  • CanMatch — decide whether a route matches at all (great for lazy loading and role-based alternates).
  • Resolve — preload data before activation.

A guard returns boolean, a UrlTree (to redirect), or a Promise/Observable of these.

The crucial 2026 update: functional guards are the standard — class-based guard interfaces were deprecated in v16. You now write a plain function and use inject():

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  return auth.isLoggedIn() ? true : inject(Router).createUrlTree(['/login']);
};
// route: { path: 'admin', canActivate: [authGuard], component: AdminComponent }

Mentioning CanMatch and functional guards signals current knowledge.

↑ Back to top

Follow-up 1

What are the different types of route guards and when would you use each?

There are three types of route guards in Angular:

  1. CanActivate: This guard determines if a route can be activated or not. It is used to prevent unauthorized access to a route. You would use this guard when you want to restrict access to a route based on certain conditions, such as user authentication.

  2. CanActivateChild: This guard is similar to CanActivate, but it applies to child routes. It is used to control access to child routes of a parent route.

  3. CanDeactivate: This guard determines if a route can be deactivated or not. It is used to prevent navigation away from a route based on certain conditions. You would use this guard when you want to prompt the user for confirmation before leaving a page or when you want to prevent unsaved changes from being lost.

Follow-up 2

How do you implement a route guard?

To implement a route guard in Angular, you need to create a guard class that implements one of the guard interfaces (CanActivate, CanActivateChild, or CanDeactivate). The guard class should define the logic for determining if a route can be activated or deactivated.

Here is an example of how to implement a CanActivate guard:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable | Promise | boolean | UrlTree {
    // Logic to determine if the route can be activated
    return true; // or false
  }

}

Follow-up 3

Can a route guard prevent navigation to a route?

Yes, a route guard can prevent navigation to a route. By returning false from the canActivate or canActivateChild methods of a guard class, you can prevent the route from being activated. This can be useful for implementing authorization checks or other conditions that need to be met before allowing access to a route.

Here is an example of how to prevent navigation to a route using a CanActivate guard:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable | Promise | boolean | UrlTree {
    // Logic to determine if the route can be activated
    if (/* condition not met */) {
      return false;
    }
    return true;
  }

}

5. How do you navigate programmatically in Angular?

Inject the Router service and call navigate() (array of path segments) or navigateByUrl() (a full URL string):

private router = inject(Router);
private route = inject(ActivatedRoute);

goToUser(id: string) {
  this.router.navigate(['/users', id], { queryParams: { tab: 'profile' } });
}
goBackUp() {
  this.router.navigate(['../'], { relativeTo: this.route });  // relative nav
}

Points worth adding: navigate() takes a commands array and supports extras like queryParams, fragment, state, and relativeTo for relative navigation; navigateByUrl() takes an absolute URL. Both return a Promise you can await to know if navigation succeeded (a guard may block it). For declarative navigation in templates, prefer routerLink — use programmatic navigation when the destination depends on logic (after a successful save, login redirect, etc.).

↑ Back to top

Follow-up 1

What is the role of the Router service in navigation?

The Router service in Angular is responsible for managing the navigation between different views or components in your application. It allows you to define routes and navigate to those routes programmatically. The Router service also handles URL parsing and generation, route activation and deactivation, and route parameter passing.

Follow-up 2

How do you pass parameters during navigation?

You can pass parameters during navigation in Angular by using the queryParams or the route parameters. Here's an example of how to pass parameters using the queryParams:

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

constructor(private router: Router) {}

navigateToProduct(productId: number) {
  this.router.navigate(['/product'], { queryParams: { id: productId } });
}

Follow-up 3

Can you explain how to use relative navigation?

Relative navigation in Angular allows you to navigate relative to the current route. It is useful when you want to navigate to a sibling or child route without specifying the entire route path. You can use the relativeTo property in the navigate() method to specify the relative route. Here's an example:

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

constructor(private router: Router, private route: ActivatedRoute) {}

navigateToChild() {
  this.router.navigate(['../child'], { relativeTo: this.route });
}

Live mock interview

Mock interview: Routing

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.