Monday, 26 March 2018

Angular 2 - Forms

Developing forms requires design skills (which are out of scope for this page), as well as framework support for two-way data binding, change tracking, validation, and error handling, which you'll learn about on this page.

Template-driven forms
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

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)