AngularJS (1.x) used ngRoute
for routing, whereas modern Angular (2+) uses the more robust @angular/router
module. If you’re upgrading an AngularJS application to Angular, you must migrate from ngRoute
to Angular Router
.
This guide will walk you through:
- The differences between
ngRoute
andAngular Router
- Step-by-step migration from
ngRoute
toAngular Router
- Best practices for routing in modern Angular
1. Understanding Differences Between ngRoute and Angular Router
Feature | ngRoute (AngularJS) | Angular Router (Angular 2+) |
---|---|---|
Module | ngRoute | @angular/router |
Configuration | $routeProvider | RouterModule.forRoot([]) |
Route Parameters | $routeParams | ActivatedRoute |
Lazy Loading | Not Supported | Supported |
Guards | Basic Check in resolve | Full Guard System (CanActivate , CanDeactivate , etc.) |
2. Step-by-Step Migration from ngRoute to Angular Router
Step 1: Remove AngularJS ngRoute
If your application is using ngRoute
, it is usually defined in a module like this:
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
}]);
Before migrating, remove the ngRoute
dependency and related configurations.
Step 2: Install Angular Router
If you are working with an Angular 2+ project, install the Angular Router package (if not already included).
npm install @angular/router
Step 3: Set Up RouterModule in Angular
Instead of using $routeProvider
, configure routes in app-routing.module.ts
using RouterModule.forRoot()
.
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: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' }, // Default route
{ path: '**', redirectTo: 'home' } // Wildcard for undefined routes
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 4: Add Router Outlet in Template
Unlike ng-view
in AngularJS, Angular 2+ uses <router-outlet>
for rendering views.
Old AngularJS Template (index.html
or app.html
)
<div ng-view></div>
New Angular Template (app.component.html
)
<router-outlet></router-outlet>
Step 5: Update Navigation Links
Old AngularJS Navigation (ng-href
)
<a ng-href="#/home">Home</a>
<a ng-href="#/about">About</a>
New Angular Navigation (routerLink
)
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
Step 6: Handling Route Parameters
If you were using $routeParams
in AngularJS, replace it with ActivatedRoute
in Angular.
Old AngularJS ($routeParams
)
angular.module('myApp').controller('ProductController', function($scope, $routeParams) {
$scope.productId = $routeParams.id;
});
New Angular (ActivatedRoute
)
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html'
})
export class ProductComponent implements OnInit {
productId!: number;
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
this.productId = Number(this.route.snapshot.paramMap.get('id'));
}
}
Step 7: Implement Route Guards (Optional)
In AngularJS, route authorization was handled inside the controller. In Angular, we use route guards.
Old AngularJS (Inside Controller)
$routeProvider.when('/admin', {
templateUrl: 'admin.html',
controller: 'AdminController',
resolve: {
check: function(AuthService) {
if (!AuthService.isAuthenticated()) {
$location.path('/login');
}
}
}
});
New Angular Route Guard
- Create Guard (
auth.guard.ts
)
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
- Apply Guard to Routes
const routes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
];
Step 8: Implement Lazy Loading (Optional, for Optimization)
Lazy loading in Angular allows loading modules on demand instead of at startup.
Old AngularJS (All Templates Loaded at Start)
$routeProvider.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'DashboardController'
});
New Angular Lazy Loading
- Create Feature Module (
dashboard.module.ts
)
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [{ path: '', component: DashboardComponent }];
@NgModule({
declarations: [DashboardComponent],
imports: [CommonModule, RouterModule.forChild(routes)]
})
export class DashboardModule { }
- Define Lazy Loading in
app-routing.module.ts
const routes: Routes = [
{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) }
];