Click here to Skip to main content
13,898,182 members
Click here to Skip to main content
Add your own
alternative version

Stats

16.9K views
456 downloads
9 bookmarked
Posted 21 Sep 2017
Licenced CPOL

Learn Angular Tutorial - Part 3

, 21 Sep 2017
Rate this:
Please Sign up or sign in to vote.
This is Part 3 of Learn Angular Tutorial. In this we will see how to implement SPA using Angular routes. Also we will be looking in to implementing Angular validations.

Contents

Lab 7 :- Implementing SPA using Angular routing

Lab 8 :- Implementing validation using Angular form

Whats in the Next article?

Links to rest of the articles

In this article we will see how to create SPA using Angular routing mechanism.

Lab 7 :- Implementing SPA using Angular routing

Fundamental of Single page application

Now a days Single page application ( SPA) has become the style of creating websites. In SPA we load only things which we need and nothing more than that.


At the right-hand side is a simple website where we have Logo and header at the top, Left menu links and footer at the bottom.

So the first time when user comes to the site all the sections of the master page will be loaded. But when user clicks on Supplier link only Supplier page will load and not logo, header and footer again. When user clicks on Customer link only Customer page will be loaded and not all other sections.

Angular routing helps us to achieve the same.

Step 1 :- Creating the Master Page

As everything revolves around the Master Page so the first logical step would be is to create the “MasterPage”.

In this master page we will create placeholders for logo , header , menu , footer , copyright and so on. These sections will be loaded only once when the user browses the website first time. And in the later times only pages which are needed will be loaded on demand.

Below is the sample HTML code which has all the placeholder sections. You can also see in this code we have kept a “DIV” tag section in which we would loading the pages on-demand.

Below is the overall main sections of “MasterPage”. Please note the “DIV” section with name “dynamicscreen” where we intend to load screens dynamically. We will fill these sections later.

<table border="1" width="448">
<tr>
<td>Logo</td>
<td width="257">Header</td>
</tr>
<tr>
<td>Left Menu</td>
<td width="257">
<div id="dynamicscreen">
  Dynamic screen will be loaded here
</div>
</td>
</tr>
<tr>
<td>Footer</td>
<td width="257">Copyright</td>
</tr>
</table>

Step 2 :- Creating the Supplier page and welcome page

Let’s create two more HTML UI one “Supplier” page and “Welcome” page.In both these HTML pages we are not doing much , we have just greeting messages.

Below is the supplier pages text.

This is the Suppliers page

Below is welcome pages text.

Welcome to the website

Step 3 :- Renaming placeholder in Index.html

As explained in Part 1 “Index.html” is the startup page and it bootstraps all other pages using systemjs. In the previous lesson inside “Index.html” , “Customer.html” page was loading. But now that we have master page so inside index page “MasterPage.html” will load.

So to make it more meaningful lets rename “customer-ui” tag to “main-ui”. In this “main-ui” section we will load the master page and when end user clicks on the master page left menu links supplier , customer and welcome pages will load.

So if look at the flow , first index.html will get loaded and then inside the “main-ui” , “masterpage.html” gets loaded.

Step 4 :- Removing selector from CustomerComponent

Now the first page to load in the index.html will be Masterpage and not Customer page. So we need to remove the selector from “CustomerComponent.ts”. This selector will be moved to masterpage component in the later sections.

The final code of “CustomerComponent.ts” would look something as show below.

import {Component} from "@angular/core"
//importing the customer model
import {Customer} from '../Model/Customer'
@Component({
    templateUrl: "../UI/Customer.html"
})
export class CustomerComponent {
    //this is binding
    CurrentCustomer:Customer = new Customer();

}

Step 5 :- Creating Components for Master , Supplier and Welcome page

Every UI which is Angular enabled should have component code file. We have created 3 user interfaces so we need three component code files for the same.

In the component folder, we will create three component TS files “MasterPageComponent.ts” , “SupplierComponent.ts” and “WelcomeComponent.ts”.

You can visualize component code files as code behind for Angular UI.

So first let’s start with “MasterPage.html” component which we have named as “MasterPageComponent.ts”. This master page will get loaded in “Index.html” in the initial bootstrapping process. You can see in this component we have put the selector and this will be the only component which will have the selector.

import {Component} from "@angular/core"

@Component({
    selector: "main-ui",
    templateUrl: "../UI/MasterPage.html"
})
export class MasterPageComponent {
}

Below is the component code for “Supplier.html”.

import {Component} from "@angular/core"

@Component({
  
    templateUrl: "../UI/Supplier.html"
})
export class SupplierComponent {
}

Below is the component code for “Welcome.html”. Both Supplier and Welcome component do not have the selector , only the master page component has it as it will be the startup UI which will get loadedin index page.

import {Component} from "@angular/core"

@Component({
    templateUrl: "../UI/Welcome.html"
})
export class WelcomeComponent {
}

Step 6 :- Creating the routing constant collection

Once the master page is loaded in the index page, end user will click on the master page links to browse to supplier page, customer page and so on.Now in order that the user can browse properly we need to define the navigation paths. These paths will be specified in the “href” tags in the later steps.

When these paths will be browsed, it will invoke the components and components will load the UI. Below is a simple table with three columns. The first column specifies the path pattern, second which component will invoke when these paths are browsed and the final column specifies the UI which will be loaded.

Path/URL Component UI which will be loaded
/ WelcomeComponent.ts Welcome.html
/Customer CustomerComponent.ts Customer.html
/Supplier SupplierComponent.ts Supplier.html

The paths and component entries needs to be defined in a simple literal collection as shown in the below code. You can see the “ApplicationRoutes” is a simple collection where we have defined path and the component which will be invoked. These entries are made as per the table specified at the top.

import {Component} from '@angular/core';
import {CustomerComponent} from '../Component/CustomerComponent';
import {SupplierComponent} from "../Component/SupplierComponent";
import {WelcomeComponent} from "../Component/WelcomeComponent";

export const ApplicationRoutes = [
    { path: 'Customer', component: CustomerComponent },
    { path: 'Supplier', component: SupplierComponent },
     { path: '', component:WelcomeComponent  }
];

As a good practice all the above code we have defined in a separate folder “routing” and in a separate file “routing.ts”.

Step 7 :- Defining routerLink and router-outlet

The navigation ( routes) defined in “Step 6” in the collectin needs to referred when we try to navigate inside the website. For example, in the master page we have defined the left menu hyperlinks.

So rather than using the “href” tag of HTML we need to use “[routerLink]”

<a href="Supplier.html">Supplier</a>

We need to use “[routerLink]” and the value of “[routerLink]” will be the path specified in the routes collection define the previous step. For example in the “ApplicationRoutes” collection we have made one entry for Supplier path we need to specify the path in the anchor tag as shown in the below code.

<a [routerLink]="['Supplier']">Supplier</a>

When the end user clicks on the left master page links the pages (supplier page, customer page and welcome page) will get loaded inside the “div” tag. For that we need to define “router-outlet” placeholder. Inside this placeholder pages will load and unload dynamically.

<div id="dynamicscreen">
<router-outlet></router-outlet>
</div>

So if we update the master page defined in “Step 1” with “router-link” and “router-outlet” we would end up with code something as shown below.

<table border="1">
<tr>
<td><img src="http://www.questpond.com/img/logo.jpg" alt="Alternate Text" />
</td>
<td>Header</td></tr><tr>
<td>Left Menu<br /><br /><br />
<a [routerLink]="['Supplier']">Supplier</a> <br /><br />
<a [routerLink]="['Customer']">Customer</a></td><td>
<div id="dynamicscreen">
<router-outlet></router-outlet>
</div>
</td>
</tr>
<tr>
<td>Footer</td><td></td>
</tr>
</table>

Step 8 :- Loading the routing in Main modules

In order to enable routing collection paths defined in “ApplicationRoutes” we need to load that in the “MainModuleLibrary” as shown in the below code. “RouterModule.forRoot” helps load the application routes at the module level.

Once loaded at the module level it will be available to all the components for navigation purpose which is loaded inside this module.

@NgModule({
    imports: [RouterModule.forRoot(ApplicationRoutes),
             BrowserModule,
             FormsModule],
    declarations: [CustomerComponent,MasterPageComponent,SupplierComponent],
    bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }

The complete code with routes would look something as shown below.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from "@angular/forms"
import { CustomerComponent }   from '../Component/CustomerComponent';
import { SupplierComponent }   from '../Component/SupplierComponent';
import { MasterPageComponent }   from '../Component/MasterPageComponent';
import { RouterModule }   from '@angular/router';
import { ApplicationRoutes }   from '../Routing/Routing';  

@NgModule({
    imports: [RouterModule.forRoot(ApplicationRoutes),
             BrowserModule,
             FormsModule],
    declarations: [CustomerComponent,MasterPageComponent,SupplierComponent],
    bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }

Step 9 :- Define APP BASE HREF

Router module requires a root path. In other words “Supplier” route would become “companyname/Supplier” , “Customer” route would become “companyname/Customer” and so on. If you do not provide a route you would end up with error as shown below.

So in your “Index.html” we need add the HTML BASE HREF tag as show in the highlighted code below . At this moment we are not providing any root directory.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
</head>
<base href="./">
<!—Other code has been removed for clarity -->

Step 10 Seeing the output

Now run the website and try to browser to UI folder and you should see the below animated video output. You can see that the logo gets loaded only once and later when the user is click on the supplier links , customer links image is not loading again and again.

Step 11 :- Fixing Cannot match any routes error

If you do a “f12” and check in the console part of the chrome browser , you would see the below error. Can you guess what the error is ?.

 

Your current angular application is route enabled. So every URL which is browsed is looked up in to routes collection.
So the first URL which you browse is “/UI” and it tries to lookup in to your routes collection and does not find one.

So that’s why it throws up the above error.

In order to fix the same make one more entry for “UI” path and point it to “WelcomeComponent”.

export const ApplicationRoutes = [
    { path: 'Customer', component: CustomerComponent },
    { path: 'Supplier', component: SupplierComponent },
     { path: '', component:WelcomeComponent  },
    { path: 'UI', component:WelcomeComponent  }

];

Understanding the flow

  1. End user loads index.html page.
  2. Index.html triggers systemjs and loads masterpage.html.
  3. When end users click on masterpage links, other pages are loaded in “router-outlet” placeholders.

Lab 8 :- Implementing validation using Angular form

In this lab we will try to understand how we can implement validations using Angular framework.

Requirement of a good validation structure

One of the important legs of software application is validations.

Validations are normally applied to user interfaces (Forms) and User interfaces have controls and on the controls, we apply validations.

 

In Angular form validation architecture structure is as follows.

At the top we have FormGroup , FormGroup has FormControls and FormControls has one or many validations.

There are 3 broader steps to implement Angular validation

  1. Create FormGroup.
  2. Create FormControl and with proper validations.
  3. Map those validations to the HTML Form.

 

What kind of validation will we implement in this Lab ?

In this lab we will implement the following validation on our Customer screen: -

  • Customer Name should be compulsory.
  • Customer code should be compulsory.
  • Customer code should be in the format of A1001, B4004 and so on. In other words the first character should be a capital alphabet followed by 4 letter numeric.

Note :- Customer code has composite validations.

Where to put Validations ?

Before even we start with validations we need to decide which is the right place to put validations. If you see in Angular we have three broader section UI , Component and Model. So let’s think over which is the right layer to put validations.

  • UI :- UI is all about look and feel and positioning of controls. So putting validation in this layer is a bad idea. Yes on this layer we will apply validations but the validation code should be in some other layer.
  • Component :- Component is the code behind ( Binding code) which binds the UI and Model. In this layer more binding related activity should be put. One component can use many models so if we put the validation logic here we need to duplicate that in other components as well.
  • Model :- A Model represents a real world entity like person , user , admin , product etc. Behavior a.k.a validations are part of the model. A model has Data and Behavior. So the right place where validations should be present is this Layer.

So let us put validation as a part of the model.

Step 1 :- Import necessary components for Angular validators

So the first step is to import the necessary components for angular validators in the customer model. All angular validator components are present in “@angular/forms” folder. We need to import five components NgForm, FormGroup, FormControl and validators.

NgForm :- Angular tags for validation.
FormGroup :- Helps us to create collection of validation.
FormControl and Validators:- Helps us to create individual validation inside FormGroup.
FormBuilder :- Helps us to create the structure of Form group and Form controls. Please note one Form group can have many FormControls.

import {NgForm,
    FormGroup,
    FormControl,
    Validators,
    FormBuilder } from '@angular/forms'

Step 2 :- Create FormGroup using FormBuilder

The first step is to create an object of FormGroup in which we will have collection of validation. The FormGroup object will be constructed using the “FormBuilder” class.

formGroup: FormGroup = null; // Create object of FormGroup
var _builder = new FormBuilder();
this.formGroup = _builder.group({}); // Use the builder to create object

Step 3 :- Adding a simple validation

Once the FormGroup object is created the next step is to add controls in the FormGroup collection. To add a control we need to use “addControl” method. The first parameter in “addControl” method is the name of the validation and second is the Angular validator type to be added.

Below is a simple code in which we are adding a “CustomerNameControl” using the “Validators.required” FormControl. Please note “CustomerNameControl” is not a reserved keyword. It can be any name like “CustControl”.

this.formGroup.addControl('CustomerNameControl', new
            FormControl('',Validators.required));

Step 4 :- Adding a composite validation

If you want to create a composite validation then you need to create a collection and add it using “compose” method as shown in the below code.

var validationcollection = [];
validationcollection.push(Validators.required);
validationcollection.push(Validators.pattern("^[A-Z]{1,1}[0-9]{4,4}$"));
this.formGroup.addControl('CustomerCodeControl', new FormControl('', Validators.compose(validationcollection)));

Full Model code with validation

Below is the full Customer Model code with all three validation as discussed in the previous section. We have also commented the code so that you can follow it.

// import components from angular/form
import {NgForm,
    FormGroup,
    FormControl,
    Validators,
    FormBuilder } from '@angular/forms'
export class Customer {
    CustomerName: string = "";
    CustomerCode: string = "";
    CustomerAmount: number = 0;
    // create object of form group
    formGroup: FormGroup = null;
   
    constructor(){
        // use the builder to create the
        // the form object
        var _builder = new FormBuilder();
        this.formGroup = _builder.group({});

        // Adding a simple validation
        this.formGroup.addControl('CustomerNameControl', new
            FormControl('',Validators.required));
       
        // Adding a composite validation
        var validationcollection = [];
        validationcollection.push(Validators.required);
        validationcollection.push(Validators.pattern("^[A-Z]{1,1}[0-9]{4,4}$"));
        this.formGroup.addControl('CustomerCodeControl', new
            FormControl('', Validators.compose(validationcollection)));
    }  
}

Step 5 :- Reference “ReactiveFormsModule” in CustomerModule.

// code has been removed for clarity.
import { FormsModule, ReactiveFormsModule } from "@angular/forms"
@NgModule({
    imports: [RouterModule.forChild(CustomerRoute),
                CommonModule,
                FormsModule,
                ReactiveFormsModule,
                HttpModule,
                InMemoryWebApiModule.forRoot(CustomerService)],
    declarations: [CustomerComponent , GridComponent],
    bootstrap: [CustomerComponent]
})
export class CustomerModule {
}

Step 6 :- Apply formGroup to HTML form

The next thing is to apply ‘formGroup’ object to the HTML form. For that we need to use “[formGroup]” angular tag in that we need to specify the “formGroup” object exposed via the customer object.

<form [formGroup]="CurrentCustomer.formGroup">
</form>

Step 7 :- Apply validations to HTML control

The next step is to apply formgroup validation to the HTML input controls. That’s done by using “formControlName” angular attribute. In “formControlName” we need to provide the form control name which we have created while creating the validation.

<input type="text" formControlName="CustomerNameControl"

[(ngModel)]="CurrentCustomer.CustomerName"><br /><br />

Step 8 :- Check if Validations are ok

When user starts filling data and fulfilling the validations we would like to check if all validations are fine and accordingly show error message or enable / disable UI controls.

In order to check if all validations are fine we need to use the “valid” property of “formGroup”. Below is a simple example where the button will be disabled depending on whether validations are valid or not. “[disabled]” is an angular attribute which enables and disables HTML controls.

<input type="button" 

value="Click" [disabled]="!(CurrentCustomer.formGroup.valid)"/>

Step 9 :- Checking individual validations

“CurrentCustomer.formGroup.valid” check all the validations of the “FormGroup” but what if we want to check individual validation of a control.

For that we need to use “hasError” function.
“CurrentCustomer.formGroup.controls['CustomerNameControl'].hasError('required')” checks that for “CustomerNameControl” has the “required” validation rule been fulfilled. Below is a simple code where we are displaying error message in a “div” tag which visible and not visible depending on whether the “hasError” function returns true or false.

Also note the “!” ( NOT) before “hasError” which says that if “hasError” is true then hidden should be false and vice versa.

<div  [hidden]="!(CurrentCustomer.formGroup.controls['CustomerNameControl'].hasError('required'))">Customer name is required </div>

Step 10 :- standalone elements

In our forms we have three textboxes “CustomerName” , “CustomerCode” and “CustomerAmount”. In these three textboxes only “CustomerName” and “CustomerCode” has validations while “CustomerAmount” does not have validations.
Now this is bit funny but if we do not specify validations for a usercontrol which is inside a “form” tag which has “formGroup” specified you would end up with a long exception as shown below.

Error: Uncaught (in promise): Error: Error in ../UI/Customer.html:15:0 caused by: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:

      
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });

      Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

      Example:

      
    <div [formGroup]="myGroup">
       <input formControlName="firstName">
       <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
    </div>
  
Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:

      
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });

      Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

      Example:

      
    <div [formGroup]="myGroup">
       <input formControlName="firstName">
       <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
    </div>

The above error can be simplified in three simple points : -

  1. It says that you have enclosed a HTML control inside a HTML FORM tag which has Angular form validations.
  2. All controls specified inside HTML FORM tag which have angular validation applied SHOULD HAVE VALIDATIONS.
  3. If a HTML control inside Angular form validation does not have validation you can do one of the below things to remove the exception: -
    • You need to specify that it’s a standalone control.
    • Move the control outside the HTML FORM tag.

Below is the code how to specify “standalone” for Angular validations.

<input type="text" [ngModelOptions]="{standalone:true}"

[(ngModel)]="CurrentCustomer.CustomerAmount"><br /><br />

Also talk about we can remove from the form control and what happens

Complete code of Customer UI with validations applied

Below is the complete Customer UI with all three validations applied to “CustomerName” and “CustomerCode” controls.

<form [formGroup]="CurrentCustomer.formGroup">
<div>
Name:
<input type="text" formControlName="CustomerNameControl"

[(ngModel)]="CurrentCustomer.CustomerName"><br /><br />
<div  [hidden]="!(CurrentCustomer.formGroup.controls['CustomerNameControl'].hasError('required'))">Customer name is required </div>
Code:
<input type="text" formControlName="CustomerCodeControl"

[(ngModel)]="CurrentCustomer.CustomerCode"><br /><br />
<div  [hidden]="!(CurrentCustomer.formGroup.controls['CustomerCodeControl'].hasError('required'))">Customer code is required </div>
<div  [hidden]="!(CurrentCustomer.formGroup.controls['CustomerCodeControl'].hasError('pattern'))">Pattern not proper </div>

Amount:
<input type="text" 

[(ngModel)]="CurrentCustomer.CustomerAmount"><br /><br />
</div>
{{CurrentCustomer.CustomerName}}<br /><br />
{{CurrentCustomer.CustomerCode}}<br /><br />
{{CurrentCustomer.CustomerAmount}}<br /><br />
<input type="button" 

value="Click" [disabled]="!(CurrentCustomer.formGroup.valid)"/>
</form>

Write reactive forms

Run and see your validation in action

Once you are done you should be able to see the validation in action as shown in the below figure.

Dirty , pristine , touched and untouched

In this lab we covered “valid” and “hasError” property and function. “formGroup” also has lot of other properties which you will need when you are working with validations. Below are some important ones.

Property Explanation
dirty This property signals if Value has been modified.
pristine This property says if the field has changed or not.
touched When the lost focus for that control occurs.
untouched The field is not touched.

Whats in the Next article?

In the next section we will look in to how to create SPA application and validations using Angular 4 . For reading the fourth part of Learn Angular click here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


You may also be interested in...

Comments and Discussions

 
QuestionHow to run attached Lab source Pin
Zubair Alam10-Dec-17 6:20
memberZubair Alam10-Dec-17 6:20 
QuestionProblematic article Pin
arielbeck5-Nov-17 2:56
memberarielbeck5-Nov-17 2:56 
AnswerRe: Problematic article Pin
Shivprasad koirala5-Nov-17 16:24
memberShivprasad koirala5-Nov-17 16:24 
QuestionComplete code of Customer UI with validations applied Pin
Member 1024302419-Oct-17 17:22
memberMember 1024302419-Oct-17 17:22 
AnswerRe: Complete code of Customer UI with validations applied Pin
Shivprasad koirala26-Oct-17 14:09
memberShivprasad koirala26-Oct-17 14:09 
SuggestionStep 5 :- Reference “ReactiveFormsModule” in CustomerModule. Pin
Ruben Suarez Alvarez17-Oct-17 6:13
memberRuben Suarez Alvarez17-Oct-17 6:13 
GeneralRe: Step 5 :- Reference “ReactiveFormsModule” in CustomerModule. Pin
Shivprasad koirala18-Oct-17 16:24
memberShivprasad koirala18-Oct-17 16:24 
GeneralRe: Step 5 :- Reference “ReactiveFormsModule” in CustomerModule. Pin
Member 1024302419-Oct-17 17:32
memberMember 1024302419-Oct-17 17:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190306.1 | Last Updated 22 Sep 2017
Article Copyright 2017 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid