Angular Routing With Navigation

Introduction

 
Routing is a mechanism used by Angular for navigating the page and displaying the appropriate page and component on the browser.
 
The Angular framework is mainly focused on and useful for SPA (Single Page Architecture). It loads a single full HTML page and dynamically loads and updates the partial page as per user request. This is achieved with the help of a router. A page of partial page loading rule and URLs is defined in the router to render or load partial pages based on user requests.
 
Angular routing helps with navigation across the application from the view of another view. It also allows us to maintain the states implement modules and loads the modules based on the role of the user.
 

Why do we use routing?

 
We access our application through a URL, such as “https://localhost:4200”. Our application is not aware of any other URL, such as “https://localhost:4200/login”. Most web applications need to support different URLs to navigate different user pages in the application. That’s where a router comes in. The angular router is an official routing library, written and maintained by the Angular Core team. It’s a JavaScript router implementation that design to work with angular and is packaged. First of all, the angular router takes care of the duties of a Javascript router. It's activated when a user requires Angular components to compose a page when a user navigates to certain URLs. It also lets the user navigate one page to another page without having the page reloaded. Furthermore, it updates the browser history so the user can use the back and forward buttons navigate back and forth between pages.
 
Angular routing allows for the following:
 
- Redirect one URL to another URL.
- Resolve data before a page is displayed
- Run script when a page is activated and or deactivated.
- Lazy load parts of our application.
 

Router-link

 
With the help of the Router-Link directive, we can link to routs of our application right from the applications. Just add the directive to HTML –elements. When the user clicks on that element, angular navigate to specified the location.
 
The router-link is the selector for the router-link directive that turns a user click into the router navigation. These directives generate our link based on the route path.
 
Server-Side RouterLink
 
For your application to work with server-side rendering, the element hosting the directive has been the link elements.
 
It is also possible to navigate to a route from code. To do so, we need the angular router.
 
Import { Router} from ‘@Angular/Router’;
Constructor (private router:Router){ }
 
We can use CLI to generate it.
 
Ng generate module app-routing—flat—module==app
 
Example:
  1. <div>    
  2.   <nav>    
  3.       <a routerLink='/register' routerLinkActive="activate">Register</a>    
  4.            
  5.        <a routerLink='/login' routerLinkActivate="activate">login</a>    
  6.        <router-outlet></router-outlet>    
  7.   </nav>    
  8.     
  9. </div>    
Index.html
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>Navigation</title>    
  6.   <base href="/">    
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">    
  9. </head>    
  10. <body>    
  11.   <welcome></welome>    
  12. </body>    
  13. </html>    
  14. <router-outlet></router-outlet>     
Main.ts
  1. import { enableProdMode } from '@angular/core';  
  2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  3.   
  4. import { AppModule } from './app/app.module';  
  5. import { environment } from './environments/environment';  
  6.   
  7. if (environment.production) {  
  8.   enableProdMode();  
  9. }  
  10.   
  11. platformBrowserDynamic().bootstrapModule(AppModule)  
  12.   .catch(err => console.error(err));  
Module.ts 
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import{RouterModule} from '@angular/router';  
  4. import { AppComponent } from './app.component';  
  5. import { registerationcomponent } from './registration/registration';  
  6. import { logincomponent } from './login/login';  
  7. import{FormsModule } from '@angular/forms';  
  8. import { welcomecomponent } from './welcome/welcome';  
  9.   
  10. @NgModule({  
  11.   declarations: [  
  12.     AppComponent,registerationcomponent,logincomponent,welcomecomponent  
  13.   ],  
  14.   imports: [  
  15.     BrowserModule,FormsModule,  
  16.     RouterModule.forRoot([  
  17.       {path: 'login',component:logincomponent},  
  18.       {path:'register',component:registerationcomponent},  
  19.       {path:'welcome',component:welcomecomponent}  
  20.     ])  
  21.   ],  
  22.   providers: [],  
  23.   bootstrap: [welcomecomponent]  
  24. })  
  25. export class AppModule { }  
Appcomponent.html
  1. <router-outlet></router-outlet>  
apcomponent.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'navigation';  
  10. }  
  11.   
  12.    
welcome.html 
  1. <div>  
  2.   <nav>  
  3.       <a routerLink='/register' routerLinkActive="activate">Register</a>  
  4.          
  5.        <a routerLink='/login' routerLinkActivate="activate">login</a>  
  6.        <router-outlet></router-outlet>  
  7.   </nav>  
  8.   
  9. </div>  
welcome.ts
  1. import{ Component} from '@angular/core';    
  2. @Component({    
  3.     selector:'welcome',    
  4.     templateUrl:'./welcome.html',    
  5.     styleUrls:['./welcome.css']    
  6. })    
  7. export class welcomecomponent{    
  8.         
  9. }     
Register.html
  1. <div class="header">    
  2.     <h2><label class="heading">REGISTERATION FORM </label></h2>    
  3. </div>    
  4.    <div class="container">    
  5.         <form (ngSubmit)="signup()">    
  6.                <label class="label"> Enter Your Name</label>            
  7.                <input type="text" [(ngModel)]="objuser.name" name="name" class="input" placeholder="Enter Your Name" require><br><br>    
  8.                <label class="label"> Enter Your Email </label>          
  9.                   <input type="text" [(ngModel)]="objuser.email" class="input" name="email" placeholder="Enter your Email" ><br><br>    
  10.                <label class="label">Enter Your Address </label>      
  11.                <input type="text" [(ngModel)]="objuser.address" class="input" name="address" placeholder="Enter Your Address"><br><br>    
  12.                 <label class="label">    
  13.                Enter Your Mobile No </label><input type="text" [(ngModel)]="objuser.mobile"class="input" name="mobile" placeholder="Enter Your Password"> <br><br>    
  14.                <label class="label">Enter Your Password </label>       
  15.                <input type="password" [(ngModel)]="objuser.password" class="input" name="password" placeholder="Enter Your Password"> <br><br>    
  16.                  
  17.                <button type="submit" class="signup">signup</button>   if allready member please click here<a routerLink='/login' routerLinkActive="activate">login</a>    
  18.     
  19.             
  20.     
  21.         </form>    
  22.     </div>     
  23.    <router-outlet></router-outlet>     
Register.css
  1. .header{  
  2.     height60px;  
  3.     width100%;  
  4.     background-color#1976d2;  
  5.     colorwhite;  
  6.     text-aligncenter;  
  7.     padding-top0px;  
  8.      margin-left40px  
  9. }  
  10. .container{  
  11.     padding-top100px;  
  12.     text-aligncenter;  
  13. }  
  14. .input{  
  15.     color:black;  
  16.     height20px;  
  17.     width150p;  
  18.     margin-left70px;  
  19.   
  20. }  
  21.   
  22. .label{  
  23.       
  24.         colorblack;  
  25.         font-size20px;  
  26.         font-styleoblique;  
  27.         font-familyVerdana, Geneva, Tahomasans-serif;  
  28.           
  29.         margin-left20px;  
  30.       
  31.       
  32. }  
  33. .signup{  
  34.     background-color#1976d2;  
  35.     text-aligncenter;  
  36.     border#1976d2;  
  37.     height30px;  
  38.     width70px;  
  39.     colorwhite;  
  40.     font-size:15px;  
  41.   
  42. }  
  43. .heading{  
  44.     padding-bottom20px;  
  45.     font-size50px;  
  46.     font-styleitalic;  
  47. }  
register.ts
  1. import {Component } from '@angular/core'  
  2. import { usermodel } from '../model/usermodel';  
  3. @Component({  
  4.     selector:'register',  
  5.     templateUrl:'./registration.html',  
  6.     styleUrls: ['./registration.css']  
  7. })  
  8. export class registerationcomponent{  
  9.     objuser:usermodel=new usermodel();  
  10.   
  11. }  
 login.html
  1. <div class="nav">    
  2.     <div class="navbar">    
  3.         <div class="heading">    
  4.                <h2>Login Form</h2>    
  5.             </div>    
  6.             <div class="container">    
  7.                  <form (ngSubmit)="loginuser()">    
  8.                   <label class="label"> Enter Your Email</label>    
  9.                               
  10.                  <input type="email" name="email" class="textable" placeholder="Enter Your Email/Username">    
  11.                           
  12.                  <br> <br>    
  13.                  <label class="label"> Enter Your Password</label>    
  14.                  
  15.                  
  16.                  <input type="password" name="password" class="password" placeholder="Enter Your password">    
  17.                  
  18.                  <br><br> <br>    
  19.                   <button type="submit" class="submit" (ngSubmit)="loginuser()" >Login</button>        
  20.                   <button type="cancel" class="cancel">Cancel</button>    
  21.     
  22.                 </form>    
  23.              </div>    
  24.           </div>    
  25. </div>    
  26. <router-outlet></router-outlet>    
login.css 
  1. nav{  
  2.     background-color: whitesmoke;  
  3.     text-aligncenter;  
  4. }  
  5. .navbar{  
  6.     background-color#1976d2;  
  7.     height50px;  
  8.     padding-top0px;  
  9.     padding-left:  0px;  
  10.     padding-right0px;    
  11. }  
  12. .heading{  
  13.     colorwhite;  
  14.     text-aligncenter;  
  15.     font-size30px;  
  16.     font-styleoblique;  
  17.   
  18. }  
  19.     .label{  
  20.         colorblack;  
  21.         font-size20px;  
  22.         font-styleoblique;  
  23.         font-familyVerdana, Geneva, Tahomasans-serif;  
  24.         padding-right50px;  
  25.     }  
  26.     .container{  
  27.         padding-top100px;  
  28.   
  29.     }  
  30.     .textable{  
  31.         colorwhite;  
  32.         height20px;  
  33.         width150p;  
  34.   
  35.     }  
  36.     .password{  
  37.         colorwhite;  
  38.         height20px;  
  39.         width150p;  
  40.   
  41.     }  
  42.     .submit{  
  43.         color:white;  
  44.         background-colorgreen;  
  45.         height30px;  
  46.         width70px;  
  47.         text-aligncenter;  
  48.         border0px;  
  49.         border-end-start-radius: 20px;  
  50.     }  
  51.     .cancel{  
  52.         color:white;  
  53.         background-colorred;  
  54.         height30px;  
  55.         width70px;  
  56.         text-aligncenter;  
  57.         border0px;  
  58.     }  
login.ts
  1. import {Component} from '@angular/core';  
  2. import { userservice } from '../service/userservice';  
  3. import { Router } from '@angular/router';  
  4. import { usermodel } from '../model/usermodel';  
  5. @Component({  
  6.     selector:'login',  
  7.     templateUrl:'./login.html',  
  8.     styleUrls: ['./login.css']  
  9.   
  10. })  
  11. export class logincomponent{  
  12.       
  13. }  
Routing.ts
  1. import{Rgoutes } from "@angular/router";  
  2. import { logincomponent } from '../login/login';  
  3. import { welcomecomponent } from '../welcome/welcome';  
  4. export const routes: Routes = [  
  5.       
  6. {path: '', component:logincomponent },  
  7. { path:'movies/:email ',component:welcomecomponent},  
  8. {path: 'login', component: logincomponent },  
  9. {path:'welcome', component:welcomecomponent},  
  10. {path: '**', component:logincomponent}   
  11.   
  12. ]  
  13.   
  14. Export class routing {  
  15. }  
Open the terminal and run the command “ ng serve”. When you run the command ng serve, your application starts to compile. After compilation, you have to go to the browser and hit localhost:4200. After a few seconds, your browser displays your application view on your screen. It should look like this:
 
Now you have seen that there are two links, login and registration. When you click on the register link, then the browser opens the registration page:
 
Here's the Registration form:
 
After opening registration, you have to click on the login link. Afterward, you have to move to the login page. 
Now you have seen Angular routing with 2 components. 
 
I hope you enjoy this article! Follow c#chamangautam to learn more about Angular and for more technology, follow C# Corner! Thank you!