Prerequisites

  • HTML
  • CSS
  • JavaScript

Angular is used in development of Single page applications(SPA). In a single page application, we are changing what the user views by showing and hiding sections of display which is responsible to particular components (rewriting the current web page with new data(code) from the server rather than getting a new HTML page requesting the server). In Angular SPA index.html is the running page and inside display components are created and routed to use.

To handle navigation from one component to another component, we use the Angular Router. The Router makes navigation after interpreting browser URL as a command to change what the viewer sees.

As mentioned in the above diagram three components are routed and we can navigate through the http://localhost:4200/path URL.

First of all We should create Default Angular Front end Application

For that We need Node.js installed in our Device.

Install angular using

npm install @angular/cli

Create New angular project using

ng new app

After Successful creation of Angular app, We have to follow through below six steps to get an understanding about angular Routing. Here I used Bootstrap to make things easier. So that I linked the Bootstrap stylesheet in index.html file.

  1. Creating Angular Components For our App
  2. Adding Components to App Module
  3. Configuring the App Routing
  4. Adding App Routing module to App Module
  5. Adding Navigation to App Component and Router Outlet
  6. Starting Angular Application

1. Creating Angular Components For our App

This Angular app contains 3 pages — Home page, Login page and Register page. So we have to create three Components which includes component.html file ,component.ts file and component.css file if needed.

First we need to Create home folder inside the app folder and then create home.component.html file inside the home folder. Here we can include whatever we wish to be showed in the home page.

<div class="jumbotron text-center" style="margin-bottom:0"><h1>Welcome to Homepage</h1>
<p>This site is working</p>
</div>

home.component.ts file links the HTML ,CSS files with app.module.tsfile. Here we are not using CSS file for the Home page. After creating home.component.ts file inside the home folder. Created a component named HomeComponent which we will export to the app.module file.Add the given Type script code in the file

import { Component } from '@angular/core';
@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {}

To make exporting files easier. We are Creating a file index.ts inside the home folder, this barrel file re-exports all components from the home folder. So now we can import them in other components and files with the folder path

'./home'

instead of using the full length path to the component

./home/home.component'

Then we added TypeScript code to the index.ts barrel file.

export * from './home.component';

Home page
Home page

Like we did earlier We have to create a HTML file.

<div class="login-form">
<form action="" method="post">
<h2 class="text-center">Log in</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" required="required">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Log in</button>
</div>
<div class="clearfix">
<label class="float-left form-check-label"><input type="checkbox"> Remember me</label>
<a href="#" class="float-right">Forgot Password?</a>
</div>
</form>
<p class="text-center"><a routerLink="/register">Create an Account</a></p>

Here we use routerLink="/register” to hyperlink the text Create Account to Signup page(localhost:4200/register).

Create file named login.component.css inside login folder, Add the given CSS code to the stylesheet:

.login-form {
width: 340px;
margin: 50px auto;
font-size: 15px;}
.login-form form {
margin-bottom: 15px;
background: #f7f7f7;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
padding: 30px;
}
.login-form h2 {
margin: 0 0 15px;
}
.form-control, .btn {
min-height: 38px;
border-radius: 2px;
}
.btn {
font-size: 15px;
font-weight: bold;
}

As we did earlier Create login.component.ts file inside the login folder. login.component.html so we need to include that using styleUrls in the component file. Add the given TypeScript code inside the file. Here we used CSS to the

import { Component } from '@angular/core';@Component({ templateUrl: 'login.component.html',
styleUrls: ['login.component.css']})
export class LoginComponent {}

Create file index.ts inside the login folder, this is a Type Script barrel file.

export * from './login.component';
Login page

After Creating register folder inside the app folder then create a file named register.component.html inside register folder. Then Add the following HTML code.

<div class="signup-form">
<form action="/examples/actions/confirmation.php" method="post">
<h2>Sign Up</h2>
<p>Please fill in this form to create an account!</p>
<hr>
<div class="form-group">
<div class="row">
<div class="col"><input type="text" class="form-control" name="first_name" placeholder="First Name" required="required"></div>
<div class="col"><input type="text" class="form-control" name="last_name" placeholder="Last Name" required="required"></div>
</div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="Password" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_password" placeholder="Confirm Password" required="required">
</div>
<div class="form-group">
<label class="form-check-label"><input type="checkbox" required="required"> I accept the <a href="#">Terms of Use</a> &amp; <a href="#">Privacy Policy</a></label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Sign Up</button>
</div>
</form>
<div class="hint-text">Already have an account? <a style="color:blue;" routerLink="/login">Login here</a></div>
</div>

Here we use routerLink="/login” to hyperlink the text Login here to Login page(localhost:4200/login).

After Creating a file register.component.css inside the login folder, Add the CSS code given below to the stylesheet:

.login-form {
width: 340px;
margin: 50px auto;
font-size: 15px;
}
.login-form form {
margin-bottom: 15px;
background: #f7f7f7;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
padding: 30px;
}
.login-form h2 {
margin: 0 0 15px;
}
.form-control, .btn {
min-height: 38px;
border-radius: 2px;
}
.btn {
font-size: 15px;
font-weight: bold;}

As we did before create a component file inside register folder and add register.component.ts file and add the TypeScript code given below.

import { Component } from '@angular/core';
@Component({ templateUrl: 'register.component.html',
styleUrls: ['register.component.css']
})
export class RegisterComponent {}

Create index.ts file inside registerfolder, this is a Type Script barrel file.

export * from './register.component';
Register page

2. Adding Components to App Module

Open the app.module.ts and add all the page components to the declarations array and for that first we need to import components using location.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';
@NgModule({
imports: [BrowserModule],
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
RegisterComponent
],
bootstrap: [AppComponent]
})
export class AppModule {};

3. Configuring the App Routing

In array of Routes ,Routing for our Angular app is configured. We define path for each component so we make the Angular Router able to know which component to display according to URL.

The RouterModule.forRoot() method creates routing module and also includes all the Angular Router directives and providers. Then the Routes array is passed to the method.

Add the given TypeScript code to app-routing.module.ts file.

import { Routes, RouterModule } from '@angular/router';import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
// otherwise the page will be redirected to the homepage
{ path: '**', redirectTo: '' }
];
export const AppRoutingModule = RouterModule.forRoot(routes);

Here { path: '**', redirectTo: '' } is used to redirect to home page whenever path we typed is wrong or not included in the App.

4. Adding App Routing Module to App Module

Open the app.module.ts then add the AppRoutingModule to the imports array and define the location while importing the file, it will result to Angular router directives and providers available to all other components which is available in the App Module.

Then make changes to the code in the app.module.ts as give below

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';
@NgModule({
imports: [BrowserModule,AppRoutingModule],
declarations: [AppComponent,HomeComponent,LoginComponent,RegisterComponent],
bootstrap: [AppComponent]})
export class AppModule {};

5. Navigation to App Component and Adding Router outlet

Open app.component.html file. The main navigation that is displayed at the top of the page is included in this file, and a main content area to be displayed in page component that is decided by the current path(localhost:4200/path) in the browser URL bar.

The routerLink directive enables the navigation between different routes along entire application , and the <router-outlet> </router-outlet> is the directive which displays the current route(code which is responsible for the view area) which is active in the Browser URL .

After the addition of the router outlet directive, the app.component.html will look like this.

<!-- navigation bar -->
<nav class="navbar navbar-expand navbar-dark bg-dark">
<div class="navbar-nav">
<a class="nav-item nav-link" routerLink="/">Home</a>
<a class="nav-item nav-link" routerLink="/login">Login</a>
<a class="nav-item nav-link" routerLink="/register">Register</a>
</div>
</nav>
<!-- main content container -->
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-sm-8 offset-sm-2">
<router-outlet></router-outlet>
<!--Here the routed component will be displayed-->
</div>
</div>
</div>
</div>

6. Starting Angular App

Run command ng serve from project root folder rootfolder/src/app to launch the Angular application.

After opening our Angular in localhost:4200 in browser. We can click Home, Login and Register and observe how the path in the URL panel and components chance accordingly. In addition to that I created hyperlink for the path change in the Login and Register components. Create Account in login.component.html and Login here in register.component.html .

The complete source code for the above Angular router example is available on GitHub at https://github.com/Akshayan98210/AngularComponentRouter

1.Download the zip file and Extract.

2.Then install Node modules Using npm install @angular/cli

3.Then run it by Entering ng serve

Nested Routes in Angular

With the basic understanding of Angular Router We can add <router-outlet></router-outlet> inside routed component and then we can display Child components in the parent components as we wish by making change in the URL.

For that in the app-routing.component.ts file first we have to import child component’s location then include path and component name by creating new children array inside corresponding parent component area inside router array.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Route1Component } from './route1';
import { Route2Component } from './route2';
import { Child1Component } from './route1/child1';
import { Child2Component } from './route1/child2';
const routes: Routes = [
{ path: 'route1', component: Route1Component ,
children: [
{path: 'child1', component: Child1Component} ,
{path: 'child2', component: Child2Component}]},
{ path: 'route2', component: Route2Component }]
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

For additional advanced information about Angular Routing make a visit to https://angular.io/guide/router.

IT Undergraduate , FIT , UOM