0
0
AngularHow-ToBeginner · 3 min read

How to Use Redirect in Angular Routing: Simple Guide

In Angular routing, use the redirectTo property inside a route configuration to automatically send users from one path to another. Combine it with pathMatch to specify how the URL is matched, usually set to 'full' for exact matches.
📐

Syntax

The redirect syntax in Angular routing uses the redirectTo property inside a route object. The path defines the URL to match, redirectTo defines the target URL, and pathMatch controls how the path is matched.

  • path: The URL segment to match.
  • redirectTo: The URL segment to redirect to.
  • pathMatch: Usually 'full' or 'prefix'. 'full' means the entire URL must match, 'prefix' means the start of the URL must match.
typescript
const routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
];
💻

Example

This example shows how to redirect the empty path '' to home. When users visit the base URL, they are automatically sent to the HomeComponent.

typescript
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';

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

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
Output
When navigating to '/', the app redirects to '/home' and displays HomeComponent.
⚠️

Common Pitfalls

One common mistake is omitting pathMatch: 'full' when redirecting an empty path. Without it, Angular uses 'prefix' by default, causing unexpected routing loops or no redirect.

Another pitfall is redirecting to a path that does not exist, which leads to a blank page or error.

typescript
const routesWrong = [
  { path: '', redirectTo: 'home' }, // Missing pathMatch
  { path: 'home', component: HomeComponent },
];

const routesRight = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
];
📊

Quick Reference

  • redirectTo: URL to redirect to.
  • pathMatch: Use 'full' for exact match redirects.
  • Always define the target route to avoid errors.
  • Redirects help guide users to default or updated pages.

Key Takeaways

Use redirectTo with pathMatch: 'full' for exact path redirects.
Always ensure the redirect target path exists in your routes.
Omitting pathMatch can cause routing errors or loops.
Redirects help set default pages or handle changed URLs smoothly.