Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular DevelopersIn Angular, navigation between pages is handled using the Angular Router.
But before navigating, routes must be registered in the Angular Router using forRoot or forFeature.
Define routes in app-routing.module.ts:
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' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
For modular applications, lazy-loaded feature modules should define their own routing using forFeature():
@NgModule({ imports: [RouterModule.forFeature([{ path: 'feature', component: FeatureComponent }])], exports: [RouterModule] }) export class FeatureRoutingModule {}
Below are different methods to navigate between pages effectively.
Use the routerLink directive to navigate between pages via templates.
Home About
This method is used for dynamic navigation inside TypeScript. We can pass an array of path segments using navigate().
To use the navigate method, import the Router service and inject it into the component.
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-example', templateUrl: './example.component.html' }) export class ExampleComponent { constructor(private router: Router) {} goToAbout() { this.router.navigate(['/about']); } }
Html file:
Used for redirections where the route is a complete string.
this.router.navigateByUrl('/about');
Both this.router.navigate() and this.router.navigateByUrl() return a Promise
this.router.navigate(['/about']).then(success => { console.log(success ? 'Navigation successful' : 'Navigation failed'); }).catch(err => console.error('Navigation error:', err));
this.router.navigateByUrl('/about').then(success => { console.log(success ? 'Navigation successful' : 'Navigation failed'); }).catch(err => console.error('Navigation error:', err));
Handling these promises is not mandatory for simple navigation, but it’s a good practice.
Used when the route has parameters and needs to pass it while navigating.
Example route:
const routes: Routes = [ { path: 'user/:id', component: UserComponent } ];
Now to navigate to above route,
this.router.navigate(['/user', 123]); // Navigates to /user/123
Query parameters allow passing additional information with the route.
this.router.navigate(['/user'], { queryParams: { name: 'John', age: 30 } });