Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
Angular routing and navigation are an integral part of web application design and development. It contributes to a presentable yet intuitive layout that makes it easier for the users to access the information quickly.
Be it a single-page application or a multi-page concept, it’s important to provide clear and understandable navigation elements to move from one view to another.
Angular offers a complete set of navigation features that work well for any simple to complex setting. The procedure, where we define the navigation elements in correspondence with their view, is what we refer as routing.
When we set up the navigation in an Angular application, we leverage a separate module, namely the RouterModule, provided by Angular. Before we head on to detail it, let’s get acquainted with its basics.
A powerful JavaScript router, the Angular router is installed from the @angular/router package. The Angular core team maintains it and Angular router offers access to a complete routing library. This library provides access to multiple router outlets, route parameters, route guards, and different path matching strategies to protect components from unauthorized access.
Further, Angular router has some essential concepts that will help in establishing smooth navigation and routing. You will find them discussed further in the article.
It is a directive available in the router library. The router inserts the components in this directive and is further matched based on the current browser’s URL. It allows you to add multiple outlets in your Angular application that comes handy to implement advanced routing scenarios. When any component matches the router, it is rendered as a sibling of the router outlet.
Routes are objects comprised of a component and a path. A path refers to the part of the URL that defines the unique view to be displayed. The path is usually empty at the beginning of any application. On the contrary, every route maps a path to the component.
Now that you are acquainted with the concepts involved in setting up navigation in your Angular application, let's move ahead with the following tasks.
Our main goal is to enable routing between the Angular components by making their routes. So when a user will click on the link, they will be navigated to the page link corresponding to the component required.
One of the best practices to start with navigation in Angular is by loading and configuring the router in a top-level yet separate module. It should be dedicated to routing imported by the root “AppModule”.
Note: AppRoutingModule is the module class name that belongs in the app-routing.module.ts in the src/app folder.
Angular CLI offers complete support while you set up routing for your web application.
So, let's create a fresh Angular application with a router enabled in it.
The below commands will help you do so.
ng new routing-app --routing
A new module namely AppRoutingModule will be created for routing purposes by Angular CLI that will have the following code.
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router';const routes: Routes = [];
@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Next, the generated AppRoutingModule will be included in AppComponent by Angular CLI as given below.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component';
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
This process will enable the AppComponent to import the AppRoutingModule module with the help of import meta data.
You can also set routing in your existing application with the help of Angular CLI.
To do so, here’s the general command you can use.
ng generate module my-module --routing
This command will generate a new module with enabled routing features. However, proceed with the following command, if you wish to enable routing features in an existing module like AppModule.
ng generate module app-routing --module app --flat
Further, the routing module needs to be configured in the ExpenseManager Application. To do so, open the command prompt. Next, open the project root folder using the following command.
cd /go/to/expense-manager
Now, use the below-given command to generate a routing module.
ng generate module app-routing --module app --flat
For all the steps followed above, CLI will generate an AppRoutingModule and will configure it in AppModule. It will look like this.
CREATE src/app/app-routing.module.ts (196 bytes) UPDATE src/app/app.module.ts (785 bytes)
The route in Angular is an object that offers information about component that maps to a specified path. These are defined by using root configuration or via instances of the routing interface.
You will come across the following properties while creating routes.
Move on and check out the code to create a simple route.
const routes: Routes = [ { path: 'about', component: AboutComponent }, ];
Once done, we will access the routes by including the router- outlet tag in the root component template followed by utilizing the routerLink and routerLinkActive properties in the required place.
<router-outlet></router-outlet><a routerLink="/about" routerLinkActive="active">First Component</a>
The routerlink mentioned above sets the route to be called while we use the path. On the contrary, the CSS class is set using routerLinkActivewhen the route is activated.
Another basic configuration for creating a simple route is given below.
import { RouterModule } from '@angular/router';@NgModule({ imports: [ ... RouterModule.forRoot([ { path: '', component: LoginComponent }, { path: 'detail', component: DetailComponent }, ]) ], })
It is a simple breakdown of how the router works by reading the URL that the user is trying to load.
If you wish to access any related part in the component, proceed with the following code where relativeTo will be available under the NavigationExtras class.
import { NavigationExtras } from '@angular/router'; this.router.navigate(['about'], { relativeTo: this.route });
Once we are done creating and accessing routes, it’s time to focus on route ordering that will take the user to where they will be redirected by clicking on a particular link.
Route ordering is an essential part of route configuration that takes the user from one view to another in web apps by matching paths.
The first match part will be called if the same part is configured multiple times. In any case, if the first match fails, the second match will be called.
To talk in detail, we will discuss how these match gets called in different scenarios.
Router redirects come in as handy for handling redirects. In it, we will look for the index path of our web app, which on loading should redirect to the login route.
Lastly, a path match key is included that tells the router how it should look up for the path.
This whole setup looks like as given below.
[ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'detail', component: DetailComponent }, ];
Using “full” dictates the router that it should compare the full path even if it ends up being something like /route1/route2/route3 or as given below.
{ path: '/route1/route2/route3', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent },
In any case, if some different path comes up like /route1/route2/route4, it won’t redirect as it doesn’t match the path completely.
Moreover, if we only use /route1/route2/, then you will be redirected to both /route1/route2/route3 and /route1/route2/route4 paths because of the matching prefix.
In lazy loading routes, the components are isolated in their own chunks rather than being included in the same chunk as the root app.module.
import { RouterModule } from '@angular/router';@NgModule({ imports: [ ... RouterModule.forRoot([ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', loadChildren: () => import('./login/login.module').then(m => m.LoginModule) }, { path: 'detail', loadChildren: () => import('./detail/detail.module').then(m => m.DetailModule) } ]) ], })
In the above-mentioned code, we refer to a module using native import with the help of loadchildren property instead of a component. So to do so, you need to create a module first for each of the components as given below.
... import { RouterModule } from '@angular/router'; import { LoginComponent } from './login.component';@NgModule({ imports: [ ... RouterModule.forChild([ { path: '', component: LoginComponent }, ]) ], })
This setup will help us produce separate chunks for the login component, the app component, and the detail component.
Angular allows you to attach extra information in the path. To do so, create a new parameter using paramMap whose syntax is given below.
const routes: Routes = [ { path: 'about', component: AboutComponent }, { path: 'item/:id', component: ItemComponent }, { path: '', redirectTo: '/about', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ];
You can use any other parameter in place of id for the information you wish to seek.
The process of Angular routing may look overwhelming. But with the above-mentioned step-by-step procedure, consider your work half done. Leverage it to cut down your efforts and set up seamless navigation on your web application in minimal time.
Srishti is a competent content writer and marketer with expertise in niches like cloud tech, big data, web development, and digital marketing. She looks forward to grow her tech knowledge and skills.