Angular 7 Routing And Preserving Trailing Slash In URL⚔️

Introduction

 
Angular Routing is an important concept to learn about. In this article, we will learn routing in Angular 2+ along with the process of preserving the trailing slash in a page URL with the addition of current page content, which means, we will retain the data of any page while doing a page refresh.
 
In simple terms, while refreshing the page, we want to remain on the same page with the same page data.
 

Routing in Angular

 
If you are new to Angular, you can read the previous article to start with Angular 2+ by clicking here. So, I am starting here by adding a new component here in my application (the application setup is already done on my system). I am adding it using the CLI command in Angular, as mentioned below.
  1. D:\DemoProject\FirstAngularApp> ng g c Home  
  2. D:\DemoProject\FirstAngularApp> ng g c AboutUs  
  3. D:\DemoProject\FirstAngularApp> ng g c ContactUs  
I have added three components in my application. After adding the above components in our application structure, it will look like below.
 
Angular 7 Routing With Preserving Trailing Slash In URL 
 
Now, let's learn and add routing in Angular 2+. Let's go to the app-routing.module.ts file (this file is auto created in Angular 7 if you choose "Yes" in the beginning of the application setup; otherwise, you have to add it manually) and add the below code for routing.
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { HomeComponent } from './home/home.component';  
  4. import { AboutUsComponent } from './about-us/about-us.component';  
  5. import { ContactUsComponent } from './contact-us/contact-us.component'  
  6.   
  7. const routes: Routes = [  
  8.   { path: '', redirectTo: 'home', pathMatch: 'full'},  
  9.   { path: 'home', component: HomeComponent },  
  10.   { path: 'about', component: AboutUsComponent },  
  11.   { path: 'contactus', component: ContactUsComponent }  
  12. ];  
  13. @NgModule({  
  14.   imports: [RouterModule.forRoot(routes)],  
  15.   exports: [RouterModule]  
  16. })  
  17. export class AppRoutingModule { }  
We have imported the components that we need to use while navigation. Now, let's add the HTML for navigation. Go to app.component.html and write the code like below.
  1.  <div style="text-align:center">  
  2.   <h1>  
  3.     Welcome to {{ title }}!  
  4.   </h1>  
  5.  </div>  
  6.  <div style="text-align:center">  
  7. <ul class="nav navbar-nav">  
  8.   <li>  
  9.     <a [routerLink]="['home']" [routerLinkActive]="['active']">Home</a>  
  10.   </li>  
  11.   <li>  
  12.     <a [routerLink]="['about']" [routerLinkActive]="['active']">About Us</a>  
  13.   </li>  
  14.   <li>  
  15.     <a [routerLink]="['contactus']" [routerLinkActive]="['active']">Contact Us</a>  
  16.   </li>  
  17. </ul>  
  18. <router-outlet></router-outlet>  
  19. </div>  
This HTML is quite simple to understand. Here, router-outlet will work like a placeholder (in ASP.NET). It will allow us to load the data of different components when we click on any particular URL in the navigation bar. Now, let's check the output by running the application.
  1. D:\DemoProject\FirstAngularApp> ng serve  
Output in the browser will be something like in the below image.
 
Angular 7 Routing With Preserving Trailing Slash In URL
 
Angular 7 Routing With Preserving Trailing Slash In URL
 
So, our application is working fine. We just implemented routing in Angular. I hope you have found everything quite simple so far. As I told earlier, we want to add a trailing slash in the URL and we want to preserve this trailing slash while refreshing the page.
 

Why trailing slash?

 
Trailing slash means a backslash at the end of the URL. Now, the question is what is the need for that. Let me explain this with an example. Suppose, we have a page URL like above http://localhost:4200/about.
 
Now, if a user tries to see this page by adding a trailing slash in the end, i.e., http://localhost:4200/about/, the page will still show the content of the page without 404 error (if rule not applied). It seems to be the same URL but Google will consider these URLs as two different links. With two URLs having the same content, the SEO rating of the content will get affected. So, to avoid this, you should either not allow the addition of trailing slash in the URL (by using 301 parament redirection) or add a trailing slash with 301. So here, we are going to add the trailing slash in the URL. So, let's change the below code in app-routing.module.ts.
  1. import { NgModule } from '@angular/core';    
  2. import { Routes, RouterModule } from '@angular/router';    
  3. import { HomeComponent } from './home/home.component';    
  4. import { AboutUsComponent } from './about-us/about-us.component';    
  5. import { ContactUsComponent } from './contact-us/contact-us.component'    
  6.     
  7. const routes: Routes = [    
  8.   { path: '', redirectTo: 'home/.', pathMatch: 'full'},    
  9.   { path: 'home/.', component: HomeComponent },    
  10.   { path: 'about/.', component: AboutUsComponent },    
  11.   { path: 'contactus/.', component: ContactUsComponent }    
  12. ];    
  13. @NgModule({    
  14.   imports: [RouterModule.forRoot(routes,{ useHash: false, initialNavigation: 'enabled' })],    
  15.   exports: [RouterModule]    
  16. })    
  17. export class AppRoutingModule { }    
We just added a backslash in the above routing and in @NgModule, just some basic settings (useHash:false, hash one of the navigation type in Angular, in which # comes with the URL).
 
Add the below code in app.module.ts.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppRoutingModule } from './app-routing.module';  
  4. import { AppComponent } from './app.component';  
  5. import { HomeComponent } from './home/home.component';  
  6. import { AboutUsComponent } from './about-us/about-us.component';  
  7. import { ContactUsComponent } from './contact-us/contact-us.component';  
  8. import {Location} from '@angular/common';  
  9.   
  10. @NgModule({  
  11.   declarations: [  
  12.     AppComponent,  
  13.     HomeComponent,  
  14.     AboutUsComponent,  
  15.     ContactUsComponent  
  16.   ],  
  17.   imports: [  
  18.     BrowserModule,  
  19.     AppRoutingModule  
  20.   ],  
  21.   providers: [],  
  22.   bootstrap: [AppComponent]  
  23. })  
  24. export class AppModule { }  
  25.   
  26. const __stripTrailingSlash = (Location as any).stripTrailingSlash;  
  27. Location.stripTrailingSlash = function (url) {  
  28.   if (url.endsWith('/')) {  
  29.     url=url;  
  30.   }  
  31.   else {  
  32.     url=url+'/';  
  33.   }  
  34.   const queryString$ = url.match(/([^?]*)?(.*)/);  
  35.   if (queryString$[2].length > 0) {  
  36.     return /[^\/]\/$/.test(queryString$[1]) ? queryString$[1] + '.' + queryString$[2] : __stripTrailingSlash(url);  
  37.   }  
  38.   return /[^\/]\/$/.test(url) ? url + '.' : __stripTrailingSlash(url);  
  39. };  
The above code will run everytime we click on the navigation URL and will check if the URL has a trailing slash or not. If not, then it will add the trailing slash in the URL before passing it to the route file to redirect any particular component. Now, let's make some changes in the HTML also because we have changed the route file by adding a backslash in the path. So, make the below changes in your app.component.html file.
  1. <!--The content below is only a placeholder and can be replaced.-->  
  2. <div style="text-align:center">  
  3.   <h1>  
  4.     Welcome to {{ title }}!  
  5.   </h1>  
  6.  </div>  
  7.  <div style="text-align:center">  
  8. <ul class="nav navbar-nav">  
  9.   <li>  
  10.     <a [routerLink]="['/home/.']" [routerLinkActive]="['active']">Home</a>  
  11.   </li>  
  12.   <li>  
  13.     <a [routerLink]="['/about/.']" [routerLinkActive]="['active']">About Us</a>  
  14.   </li>  
  15.     
  16.   <li>  
  17.     <a [routerLink]="['/contactus/.']" [routerLinkActive]="['active']">Contact Us</a>  
  18.   </li>  
  19. </ul>  
  20. <router-outlet></router-outlet>  
  21. </div>  
We are done with the changes now. Let's run our application to check the changes.
  1. D:\DemoProject\FirstAngularApp> ng serve  
Here is the output in the browser.
 
Angular 7 Routing With Preserving Trailing Slash In URL
 
Angular 7 Routing With Preserving Trailing Slash In URL
 
We can see that now the URL is coming with a trailing slash. You can remove the last trailing slash and hit Enter. Still, you will see the content of that page and the URL with a trailing slash. In this article, we have learned simple Routing and Routing with trailing slash in Angular. Hope it will help you.
 
Happy coding!!


Similar Articles