Monday 26 March 2018

Angular Forms

Angular provides two different approaches to handling user input through forms: reactive and template-driven. Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.

Template driven: With the template driven approach you basically apply directives, such as ngModel, in your template. Based on these directives Angular will create formcontrol objects. This approach is good for building simple forms with basic validation (required, minlength, maxlength,...).

Reactive forms: With the reactive approach you basically need to create new instances of the formcontrols and formcontrolgroups in your component. Reactive forms are the best choice for building complex forms and are better in case you have the intention to implement unit testing for your formsClick here for example

Choosing an approach
Reactive forms and template-driven forms process and manage form data differently. Each approach offers different advantages.

Reactive forms provide direct, explicit access to the underlying forms object model. Compared to template-driven forms, they are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.

High-level Differences between Template-driven and Reactive Forms
Below are some of the high-level differences between the two types:
  • Template-driven forms make use of the "FormsModule", while reactive forms are based on "ReactiveFormsModule".
  • Template-driven forms are asynchronous in nature, whereas Reactive forms are mostly synchronous.
  • In a template-driven approach, most of the logic is driven from the template, whereas in reactive-driven approach, the logic resides mainly in the component or typescript code. 
Template-driven forms rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They're easy to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.

Reactive form can be used in the following situation
  • Complex forms with more number of fields.
  • Multiple complex validation are there. Custom validations are required
  • Require JSON structure to be send with the values in the form.
  • We can get entire form in a structured way by using "form.value"
If we have 4 fields First Name, Last Name, Email, Phone Number in reactive form.

HTML code will be

<form [formGroup]="form">
    First Name <input formControlName="firstName">
    Last Name <input formControlName="lastName">
    Email <input formControlName="email">
    Phone Number <input formControlName="phoneNumber">
</form>

We can get the values from the form like below
{
"firstName": "FName",
"lastName": "LName",
"email": "test@123.com",
"phoneNumber": "123"
}
by calling form.value, where form is FormGroup Variable that we created.

Template Driven Form : It can be used when using simple forms. Like login page. With the two way data binding. We can simply assign value to variable from ui and vice versa.

Simple example is if we are givng two way binding for the below input.
<input [(ngModel)]="username">

We can simply display the value that user is giving in the UI.
<p>Hello {{username}}!</p>

You can build forms by writing templates in the Angular template syntax with the form-specific directives and techniques described in this page.

You'll learn to build a template-driven form that looks like this:

1- Create a new project named EmployeeForm:
ng new EmployeeForm

2- Chnage the directory
cd EmployeeForm

3- Install the angular forms module in your project 
npm install Forms

4- Add the Employee Model class
ng generate class EmployeeModel

It will generate a employee-model.ts file insrc/app directory.

5- Add members in the class file.

export class EmployeeModel {
public employeename: string ;
public Email: string;
public Username:string;
public Password: string;
}


6- Add a new Component named empcomponent

ng generate component empcomponent

It will generate required files for component in app directory. see the below screenshot.


7- Add the Form Module and newly created component in AppModule class.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { EmpComponentComponent } from './emp-component/emp-component.component';

@NgModule({
  declarations: [
    AppComponent,
    EmpComponentComponent
  ],
  imports: [
    BrowserModule, FormsModule
  ],
  providers: [],
  bootstrap: [EmpComponentComponent]
})
export class AppModule { }

8- Add the below html in emp-component.component.html file.

<div class = "container">
   <h1>Employee Form</h1>
   <form #form="ngForm" class="form-horizontal" (ngSubmit)="SaveData(form)">

  <div class="form-group">
    <label class="col-sm-2 control-label">Name</label>
    <div class="col-sm-10">
      <input type="text" name="employeename" class="form-control" #employeename="ngModel" [(ngModel)]="model.employeename" required />
      <div *ngIf="employeename.errors && (form.submitted || employeename.dirty)" class="text-danger">
        <span [hidden]="!employeename.errors.required">Please Enter Name</span>
      </div>
    </div>
  </div>
<div class="form-group">
    <label class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="text" name="Email" class="form-control" #Email="ngModel" [(ngModel)]="model.Email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/>
      <div *ngIf="Email.errors && (form.submitted || Email.dirty)" class="text-danger">
        <span [hidden]="!Email.errors.required">Please Enter Email</span>
        <span [hidden]="!Email.errors.pattern">Please Enter Correct Email</span>
      </div>
    </div>
  </div>
    <div class="form-group">
    <label class="col-sm-2 control-label">Username</label>
    <div class="col-sm-10">
      <input type="text" name="Username" class="form-control" #Username="ngModel" [(ngModel)]="model.Username" required minlength="3"/>
      <div *ngIf="Username.errors && (form.submitted || Username.dirty)" class="text-danger">
        <span [hidden]="!Username.errors.required">Please Enter Username</span>
        <span [hidden]="!Username.errors.minlength">Username must have atleast 3 chars</span>
      </div>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" name="Password" class="form-control" #Password="ngModel" [(ngModel)]="model.Password" required />
      <div *ngIf="Password.errors && (form.submitted || Password.dirty)" class="text-danger">
        <span [hidden]="!Password.errors.required">Please Enter Password</span>
      </div>
    </div>
  </div>

 <div class="form-group">
    <div class="col-sm-10 col-sm-offset-2">
      <button type="submit" class="btn btn-primary">Register</button>
    </div>
  </div>
   </form>
</div>

9- Add the below required code in emp-component.component.ts file

import { Component, OnInit } from '@angular/core';
import { EmployeeModel } from '../employee-model';
import { NgForm } from "@angular/forms";

@Component({
  selector: 'app-emp-component',
  templateUrl: './emp-component.component.html',
  styleUrls: []
})
export class EmpComponentComponent implements OnInit {

  model: EmployeeModel;
  constructor() { 
     this.model = new EmployeeModel();
  }
  SaveData(form: NgForm) {
    if (form.valid) {
      console.log(this.model);
      alert('valid!');
    }
  }
  ngOnInit() {
  }
}

10- Now replace the app-root component with emp-component in index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>EmployeeForm</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>
  <!-- <app-root></app-root> -->
  <app-emp-component></app-emp-component>
</body>
</html>

11- Now all the task has been done. now run the application.

ng serve
12- You can see the validation error in the above form. with the correct data form will be submitted.

13- Fill the correct data and click on Register button. It will display the message from server side.

All Done!


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives