For Developers

How to Make Navigation and Routing Possible in Angular 8?

Navigation and Routing in Angular 8

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.

Introducing Angular routing

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.

Steps of Angular routing.webp

Angular router

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.

  • Router outlet

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 and paths

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.

Configure routing

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 { }

Code source

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.

Setting routing in an existing application

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)

Create routes

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.

  • path is a string or a fragment of a URL that specifies the location of the resource you wish to access.

  • pathMatch is a string that defines the matching strategy and can take prefix (default) or full.

  • component specifies which component will be mapped to the route.

  • redirectTo is the URL that you will be redirected to if a route gets matched.

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 },
  ])
  ],
})

Code source

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

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.

  • Redirects

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.

  • Lazy loading routes

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.

Accessing route parameters

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.

Author

  • Author

    Srishti Chaudhary

    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.

Frequently Asked Questions

Lazy loading in Angular is a way that enables the developer to load the components of JavaScript asynchronously when a specific route gets activated. It enhances the loading time of the application and the overall user experience.

Wildcard route in Angular application handles the invalid URLs. When a user enters an invalid URL or if any existing URL is deleted from the application, then they will be directed to the 404 page stating no page found.

forchild is known to create a module. It includes all the given routes and directives. However, it does not include the router service.

To test a router navigate in Angular 8, follow the below given steps:

Step 1: Go to '@angular/router' and import router from @angular/import.

Step 2: Next, add the imported router to the providers array.

Step 3: Then, swap it out to create a routerSpy.

Step 4: Lastly, create a jasmine spy that will show you the navigation of the router in Angular 8.

Navigation in Angular takes you from one view to another. It happens when you click on a button, link, or search for the URL from the browser address bar.

The best practice to enable routing in Angular 8 is by loading and configuring the router in a top-level module separately. This router is imported by the root AppModule that belongs in the app-routing and is dedicated to routing.

View more FAQs
Press

Press

What's up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work.
Checkout our blog here.
Contact

Contact

Have any questions?
We'd love to hear from you.

Hire and manage remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.

Hire Developers