Angular Components & Routing

Prerequisites

  • HTML
  • CSS
  • JavaScript

What is routing in Angular

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

Create Home Page Template(HTML)

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

Create Home page Component(TS)

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

Create Login Page Template(HTML)

<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 Login Page Style sheet(CSS)

.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;
}

Create Login page Component(TS)

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

Create Register Page Template(HTML)

<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).

Create Register page Stylesheet (CSS)

.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;}

Create Register page Component(TS)

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

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

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

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

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

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