Connect with us

## What is Routing?

Routing means navigation between pages. It enables developers to build a Single Page Application (SPA) with multiple views and allow navigation between views.

### How does routing work?

Whenever we creating an angular project, the app-routing.modules.ts file is automatically created, which is a core file of routing to handle all the routes.

 import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } 

• Router Module and Routes are an inbuilt angular module that imports from the @angular/router package.
• MedicaidRoutes array will contain all the routes of the application. We can export the routing RouterModule in the export array.
• Medicaid We can add the RouterModule.forRoot(routes) in the import array. RouterModule defines the routing module and forRoot() specifies that this is the root routing module.
• Medicaid If we creating a custom routing, then creating components and you will add the routes in the routes array.

Step-1:

We can create components using this command:
 ng g component first ng g component second ng g component pagenotfound 
Step-2:

app-routing.modules.ts file, we can import the components and define our routes.
 import { FirstComponent } from './first/first.component'; import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component'; import { SecondComponent } from './second/second.component'; 

We can define our routes in the routes array.
 const routes: Routes = [ { path: '', redirectTo: '/first', pathMatch: 'full' }, { path: 'first', component: FirstComponent }, { path: 'second', component: SecondComponent }, ]; 

path: describes the URL of the route

component: describes the component that we will display and mapped to the route.

redirectTo: redirect to the URL if a route is matched.

pathMatch: describes how to match the URL.

There are two values in a pathMatch property:

• full: full means check the fully match route’s path.
• prefix: It’s the default value. We can use the prefix to check if the start of the URL is prefixed with the route’s path.

Step-3:

We are using angular bootstrap for better design and install the bootstrap using this command:

npm install bootstrap --save

After that installing bootstrap, add the bootstrap in the angular.json file.
 "styles": [ "src/styles.scss", "node_modules/bootstrap/dist/css/bootstrap.min.cs" ], 

Step-4:

What is a Router Outlet?

Router-outlet is used to load the different components based on the activated route. Router-outlet is a directive that is available in the router library. You can add the multiple router-outlet in your application.

<router-outlet></router-outlet>

For enabling routing, we need to use router-outlet into HTML template like:

• If we are on the first page, then-current selected menu item should be first and if we navigate the second page, then the currently selected item should be second.
• To display the currently selected route in the navbar, we can use the routerLinkActive directive.
• In the above example, add the active class if the route matches the current route in the routerLink.

### What is Wildcard Routing?

The Wildcard Routing is used to handle invalid URL’s from user side. If the user enters some invalid URL then 404 page not found error page is displayed. In that case, instead of showing the default error page, we can create our custom component using Angular Wildcard routing.

{ path: ‘**’ , component: PageNotFoundComponent }

app-routing.modules.ts, we can define wildcard string using asterisks ( ‘ ** ’ ) .
 const routes: Routes = [ { path: '', redirectTo: '/first', pathMatch: 'full' }, { path: 'first', component: FirstComponent }, { path: 'second', component: SecondComponent }, { path: '**', component: PagenotfoundComponent }, ]; 

“ ** ”  stands for URL or path does not match to any path defined in routing then display page-not-found component.

Note: Wildcard route must be declared in the last, otherwise if you add route path first then no other routes will work, and by default page not found component will be displayed.
Display the message page not found in the pagenotfoundcomponent.html file using the following code:

#### Nesting Routing

Nested Routing means routing inside the routing. We can create nested routing using child routes using the children property.

To create a nested routing, we can create child components using this command:

ng g component childA
ng g component childB

Update your routes in the app-routing.modules.ts file, we can define our child routes.
 const routes: Routes = [ { path: '', redirectTo: '/first', pathMatch: 'full' }, { path: 'first', component: FirstComponent }, { path: 'second', component: SecondComponent , children: [ { path: 'childA', component: ChildAComponent }, { path: 'childB', component: ChildBComponent }, ], }, ]; 

Also, we need to update first.component.html,

When user click the second link, then loads the second component and it’s child component ChildA and ChildB.(http://localhost:4200/second)

If the user clicked on the chiledA link, then load the ChildA Component(http://localhost:4200/second/childA) .

You can add the router-outlet for display the ChildA component. If you don’t want to add the router-outlet, then the child component will not be displayed.

#### Route Guards

An angular route guard is mainly used for authentication. It enables you to allow or disallow your specific routes based on some condition.

You can add the route guard by implementing the CanActive() available from the @angular/router package.

There are different types of route guard available in angular:

• [1] CanActivate: checks if the route can be activated.
• [2] CanActivateChild: checks if the children’s route can be activated.
• [3] CanDeactivate: checks if the user can leave the route.
• [4] Resolve: use this guard to pre-fetch the data before route activation.

 class MyGuard implements CanActivate { canActivate() { return true; } }

After that, you can add the canActivate property to protect a specific route with the using guard.
 { path: ‘products/:id’, canActivate:[MyGuard], component: ProductDetailComponent }

#### Conclusion

We have seen the importance of Routing in Angular and learned how practically it works. Angular has impeccable features such as faster rebuild time possible because of Ivy, fine type-checking, bundle-size minimization, debugging, etc. All these make the popularity of Angular and impels the people to adopt it for their web development.

Vinod Satapara – Technical Director, iFour Technolab Pvt Ltd

Technocrat and entrepreneur with years of experience building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and have been associated with Angular Frontend development companies.