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:
- <div>
- <nav>
- <a routerLink='/register' routerLinkActive="activate">Register</a>
-
- <a routerLink='/login' routerLinkActivate="activate">login</a>
- <router-outlet></router-outlet>
- </nav>
-
- </div>
Index.html
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Navigation</title>
- <base href="/">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" type="image/x-icon" href="favicon.ico">
- </head>
- <body>
- <welcome></welome>
- </body>
- </html>
- <router-outlet></router-outlet>
Main.ts
- import { enableProdMode } from '@angular/core';
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
-
- import { AppModule } from './app/app.module';
- import { environment } from './environments/environment';
-
- if (environment.production) {
- enableProdMode();
- }
-
- platformBrowserDynamic().bootstrapModule(AppModule)
- .catch(err => console.error(err));
Module.ts
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import{RouterModule} from '@angular/router';
- import { AppComponent } from './app.component';
- import { registerationcomponent } from './registration/registration';
- import { logincomponent } from './login/login';
- import{FormsModule } from '@angular/forms';
- import { welcomecomponent } from './welcome/welcome';
-
- @NgModule({
- declarations: [
- AppComponent,registerationcomponent,logincomponent,welcomecomponent
- ],
- imports: [
- BrowserModule,FormsModule,
- RouterModule.forRoot([
- {path: 'login',component:logincomponent},
- {path:'register',component:registerationcomponent},
- {path:'welcome',component:welcomecomponent}
- ])
- ],
- providers: [],
- bootstrap: [welcomecomponent]
- })
- export class AppModule { }
Appcomponent.html
- <router-outlet></router-outlet>
apcomponent.ts
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title = 'navigation';
- }
-
-
welcome.html
- <div>
- <nav>
- <a routerLink='/register' routerLinkActive="activate">Register</a>
-
- <a routerLink='/login' routerLinkActivate="activate">login</a>
- <router-outlet></router-outlet>
- </nav>
-
- </div>
welcome.ts
- import{ Component} from '@angular/core';
- @Component({
- selector:'welcome',
- templateUrl:'./welcome.html',
- styleUrls:['./welcome.css']
- })
- export class welcomecomponent{
-
- }
Register.html
- <div class="header">
- <h2><label class="heading">REGISTERATION FORM </label></h2>
- </div>
- <div class="container">
- <form (ngSubmit)="signup()">
- <label class="label"> Enter Your Name</label>
- <input type="text" [(ngModel)]="objuser.name" name="name" class="input" placeholder="Enter Your Name" require><br><br>
- <label class="label"> Enter Your Email </label>
- <input type="text" [(ngModel)]="objuser.email" class="input" name="email" placeholder="Enter your Email" ><br><br>
- <label class="label">Enter Your Address </label>
- <input type="text" [(ngModel)]="objuser.address" class="input" name="address" placeholder="Enter Your Address"><br><br>
- <label class="label">
- Enter Your Mobile No </label><input type="text" [(ngModel)]="objuser.mobile"class="input" name="mobile" placeholder="Enter Your Password"> <br><br>
- <label class="label">Enter Your Password </label>
- <input type="password" [(ngModel)]="objuser.password" class="input" name="password" placeholder="Enter Your Password"> <br><br>
-
- <button type="submit" class="signup">signup</button> if allready member please click here<a routerLink='/login' routerLinkActive="activate">login</a>
-
-
-
- </form>
- </div>
- <router-outlet></router-outlet>
Register.css
- .header{
- height: 60px;
- width: 100%;
- background-color: #1976d2;
- color: white;
- text-align: center;
- padding-top: 0px;
- margin-left: 40px
- }
- .container{
- padding-top: 100px;
- text-align: center;
- }
- .input{
- color:black;
- height: 20px;
- width: 150p;
- margin-left: 70px;
-
- }
-
- .label{
-
- color: black;
- font-size: 20px;
- font-style: oblique;
- font-family: Verdana, Geneva, Tahoma, sans-serif;
-
- margin-left: 20px;
-
-
- }
- .signup{
- background-color: #1976d2;
- text-align: center;
- border: #1976d2;
- height: 30px;
- width: 70px;
- color: white;
- font-size:15px;
-
- }
- .heading{
- padding-bottom: 20px;
- font-size: 50px;
- font-style: italic;
- }
register.ts
- import {Component } from '@angular/core'
- import { usermodel } from '../model/usermodel';
- @Component({
- selector:'register',
- templateUrl:'./registration.html',
- styleUrls: ['./registration.css']
- })
- export class registerationcomponent{
- objuser:usermodel=new usermodel();
-
- }
login.html
- <div class="nav">
- <div class="navbar">
- <div class="heading">
- <h2>Login Form</h2>
- </div>
- <div class="container">
- <form (ngSubmit)="loginuser()">
- <label class="label"> Enter Your Email</label>
-
- <input type="email" name="email" class="textable" placeholder="Enter Your Email/Username">
-
- <br> <br>
- <label class="label"> Enter Your Password</label>
-
-
- <input type="password" name="password" class="password" placeholder="Enter Your password">
-
- <br><br> <br>
- <button type="submit" class="submit" (ngSubmit)="loginuser()" >Login</button>
- <button type="cancel" class="cancel">Cancel</button>
-
- </form>
- </div>
- </div>
- </div>
- <router-outlet></router-outlet>
login.css
- nav{
- background-color: whitesmoke;
- text-align: center;
- }
- .navbar{
- background-color: #1976d2;
- height: 50px;
- padding-top: 0px;
- padding-left: 0px;
- padding-right: 0px;
- }
- .heading{
- color: white;
- text-align: center;
- font-size: 30px;
- font-style: oblique;
-
- }
- .label{
- color: black;
- font-size: 20px;
- font-style: oblique;
- font-family: Verdana, Geneva, Tahoma, sans-serif;
- padding-right: 50px;
- }
- .container{
- padding-top: 100px;
-
- }
- .textable{
- color: white;
- height: 20px;
- width: 150p;
-
- }
- .password{
- color: white;
- height: 20px;
- width: 150p;
-
- }
- .submit{
- color:white;
- background-color: green;
- height: 30px;
- width: 70px;
- text-align: center;
- border: 0px;
- border-end-start-radius: 20px;
- }
- .cancel{
- color:white;
- background-color: red;
- height: 30px;
- width: 70px;
- text-align: center;
- border: 0px;
- }
login.ts
- import {Component} from '@angular/core';
- import { userservice } from '../service/userservice';
- import { Router } from '@angular/router';
- import { usermodel } from '../model/usermodel';
- @Component({
- selector:'login',
- templateUrl:'./login.html',
- styleUrls: ['./login.css']
-
- })
- export class logincomponent{
-
- }
Routing.ts
- import{Rgoutes } from "@angular/router";
- import { logincomponent } from '../login/login';
- import { welcomecomponent } from '../welcome/welcome';
- export const routes: Routes = [
-
- {path: '', component:logincomponent },
- { path:'movies/:email ',component:welcomecomponent},
- {path: 'login', component: logincomponent },
- {path:'welcome', component:welcomecomponent},
- {path: '**', component:logincomponent}
-
- ]
-
- Export class routing {
- }
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!