Routing allows single-page applications to transition between multiple views in order to complete specific tasks. Angular Router can be utilized to manage navigation from one view to another. This is achieved by altering the browser URL, which serves as an instruction to switch views.
Creating Routes
Suppose we have three menu options in the application, and selecting each one should navigate to its corresponding view component.
To set up the routing, create a new constant called appRoutes with the type Routes in the module. This constant will store all the routes for the app/module.
The constant appRoutes is an array containing all the routes for the app/module. Each route is defined as a JavaScript object, which includes at least a path and a component (redirectTo) attribute. The path refers to the portion of the URL that determines a unique view to be displayed, while the component refers to the Angular component associated with the path.
The path can be assigned a wildcard string, which will be navigated if the requested URL does not match any of the defined routes.
Below is a straightforward example of routes defined in the appRoutes array.
const appRoutes: Routes = [
{ path: '', component: HomeComponent }, //localhost:4200
{ path: 'users', component: UserComponent },//localhost:4200/users
{ path: 'orders', component: OrdersComponent },//localhost:4200/orders
];
The next step is to register the routes defined in the appRoutes array using the 'RouterModule.forRoot()' method within the imports section of the module. The 'forRoot()' method accepts an array of route objects as input, which we have already established in the appRoutes array.
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'users', component: UserComponent },
{ path: 'orders', component: OrdersComponent },
];
@NgModule({
declarations: [],
imports: [BrowserModule, FormsModule, RouterModule.forRoot(appRoutes)],
})
Note: The Angular displays the selected route view where we add a special directive '<router-outlet></router-outlet>' which marks the place where we want the Angular router to load the component of the currently selected route.
Navigating with Router Links
Angular offers the routerLink directive, which is utilized in templates to generate links for navigating between routes. This routerLink directive takes a path as input and automatically updates the URL while rendering the corresponding component.
<ul class="nav nav-tabs">
<li role="presentation" class="active"><a routerLink="/">Home</a></li>
<li role="presentation"><a routerLink="/orders">Orders</a></li>
<li role="presentation"><a [routerLink]="['/users']">Users</a></li>
</ul>
In Angular routing, two types of paths are used for navigating between routes: absolute paths and relative paths.
- Absolute Path Routing
An absolute path specifies the complete path from the application's root to a specific route. It always begins with a forward slash ("/") and provides the full URL. Absolute paths are typically employed when you wish to navigate directly to a particular route, regardless of the current route or component.
// Absolute path routing
//localhost:4200/users
<a [routerLink]="['/users']">Users</a>
- Relative Path Routing
A relative path is determined by the current route or component. It specifies the path in relation to the current route's URL. Relative paths are helpful when you want to navigate in relation to the present route or when you need to dynamically create URLs based on the existing route.
// Relative path routing
// consider current path is users
// with below route the navigated URL will be
// localhost:4200/users/details
<a [routerLink]="['details']">Edit</a>
Navigating Programmatically
In Angular, programmatic navigation allows you to transition between routes based on specific conditions or events by using the Router service. The Router service offers the following methods:
- navigate() - This method is used to navigate to a specific route based on a provided URL or route configuration. It accepts a route path or an array of route segments as its first parameter. Optionally, you can provide an object as the second parameter to control the navigation behavior.
import { Router, ActivatedRoute } from '@angular/router';
constructor(private router: Router, private route: ActivatedRoute) {}
// Navigating to a specific route
this.router.navigate(['/orders']);
// Navigating with query parameters
this.router.navigate(['/orders'], { queryParams: { orderId: 1 } });
// Navigating with route parameters
this.router.navigate(['/orders', orderId]);
// Navigating with relative paths
this.router.navigate(['orderDetails'], { relativeTo: this.route} ]);
- navigateByUrl() - This method is utilized for navigating to a specific route according to a given URL string. It takes a URL string as its primary argument and an optional object as the second argument.
import { Router } from '@angular/router';
constructor(private router: Router) {}
// Navigating to a specific URL
this.router.navigateByUrl('/orders');
// Navigating to a URL with query parameters
this.router.navigateByUrl('/orders?orderId=1');
- navigateByRouteId() - This function is utilized to navigate to a specific route according to the route's ID. It takes the route ID as its parameter.
import { Router } from '@angular/router';
constructor(private router: Router) {}
// Navigating to a route by its ID
this.router.navigateById(1);
Note: Unlike the routerLink, the navigate() method does not recognize the current route it is on. The navigate() method always navigates from the root component ('/' i.e., localhost:4200) regardless of whether the path is absolute or relative. In contrast, routerLink navigates from the current route path it is on. Therefore, we need to use absolute or relative paths cautiously according to our requirements when working with routerLink.
//from root - localhost:4200
<a routerLink="/">Home</a>
//from root(relative path - localhost:4200/orders
<a routerLink="orders">Orders</a>
//from root(absolute path) - localhost:4200/orders
<a routerLink="/orders">Orders</a>
//from root using property binding - localhost:4200/orders
<a [routerLink]="['/orders']">Orders</a>
//from order - localhost:4200/orders/order-details
<a routerLink="order-details">Order Details</a>
//localhost:4200/orders
this.router.navigate(['orders']);
//localhost:4200/orders
this.router.navigate(['/orders']);
//from order - localhost:4200/orders/order-details
this.router.navigate(['order-details'], { relativeTo: this.activatedRoute });