Show Menu
Cheatography

Angular 2 Forms Cheat Sheet by

This cheat sheet has a quick overview of the important aspects of using Angular 2 Forms.

Introd­uction

A form creates a cohesive, effective, and compelling data entry experi­ence. An Angular form coordi­nates a set of data-bound user controls, tracks changes, validates input, and presents errors.

Form

<form>
  .... tags that include all input elements
</form>
All forms are placed within the HTML form tags

Standard Input Types

Text Input
<input type="t­ext­">
Email Input
<input type="e­mai­l">
Password Input
<input type="p­ass­wor­d">
Dropdown Selection
<se­lec­t>
<option value=­"­vol­vo">­Vol­vo<­/op­tio­n>
<option value=­"­saa­b">S­aab­</o­pti­on>
<option value=­"­ope­l">O­pel­</o­pti­on>
<option value="audi">Audi</option>
</s­ele­ct>
Multi Selection
<select multip­le>
<option value=­"­vol­vo">­Vol­vo<­/op­tio­n>
<option value=­"­saa­b">S­aab­</o­pti­on>
<option value=­"­ope­l">O­pel­</o­pti­on>
<option value="audi">Audi</option>
</s­ele­ct>
Checkbox
<input type="c­hec­kbo­x">
Radio Control
<input type="r­adi­o">
Numeric Input
<input type="n­umb­er">
Date
<input type="d­ate­">
Multiline Input
<te­xtarea rows="4­" cols="5­0"><­/te­xta­rea>

Angular 2 Form - Elements

FormGroup
A FormGroup aggregates the values of each child FormCo­ntrol into one object, with each control name as the key
FormCo­ntrol
Tracks the value and validation status of an individual form control. It is one of the three fundam­ental building blocks of Angular forms
FormArray
Tracks the value and validity state of an array of FormCo­ntrol instances. A FormArray aggregates the values of each child FormCo­ntrol into an array
FormBu­ilder
Creates an Abstra­ctC­ontrol from a user-s­pec­ified config­ura­tion. It is essent­ially syntactic sugar that shortens the new FormGr­oup(), new FormCo­ntr­ol(), and new FormAr­ray() boiler­plate that can build up in larger form
Requires use of FormModule
 

Reactive Form Names

formGr­oupName
Used to reference a group of elements
formCo­ntr­olName
Similar to ngModel reference to a name but simpler from a naming convention perspe­ctive
formAr­rayName
Syncs a nested FormArray to a DOM element.
Requires the use of the Reacti­veF­orm­sModule Module

Handling Submission Event

<form (ngSubmit)="onSubmit()">
...
</form>

Standard Validation

Mandatory
Valida­tor­s.r­equired
Minimum Length
Valida­tor.mi­nLe­ngt­h(size)
Maximum Length
Valida­tor­s.m­axL­eng­th(­size)
Pattern Match
Valida­tor­s.p­att­ern­("re­gEx­")

Custom Validators

function {name}(control : FormControl) : {[s: string] : boolean} {
  
.... function body....

pass return a null

fail return an object of type {key : true}


}

Displaying Validator Failures

        <label for="name">Name</label>
        <input type="text" class="form-control" id="name"
               required
               [(ngModel)]="model.name" name="name"
               #name="ngModel" >
        <div [hidden]="name.valid || name.pristine" 
             class="alert alert-danger">
          Name is required
        </div>

Workflow

Steps to creating a reactive form:

1. Create the Domain Model
2. Create the Controller with references to View
3. Create the View
4. Add Valida­tions
5. Add Submit Validation Control
6. Add Dynamic Behaviors
 

Model

export interface {ModelName} {

   item(? : optional) : string | number | date | boolean | class | interface ([] : array);


}

Controller

let style = require('./someStyle.css');
let template = require("./someTemplate.html");


@Component({

  styles:[style],
  template: template


});
export class {Some}Form implements OnInit{
  
  myForm: FormGroup;

  constructor(private fb : FormBuilder) {};

  ngOnInit() {
    //Construct the form data type
 
   this.myForm: this.fb.group({
       'controlName' : this.fb.control(...),
       'controlArray' : this.fb.array([...]),
       'controlGroup' : this.fb.group({})
  });

  }
 
 onSubmit() {
   myForm.value; //returns the form values
  
   myModel = <MyModel>myForm.value;//Cast to object



 }
}
Typical additions include:

1. Http Service Submission (delegate normally injected)
2. Pipes for Display custom­ization
3. Model based Validators

View

<form [formGroup]='myForm' (ngSubmit)='onSubmit()'>

  <input formControlName=''>

  <div formGroupName=''>
      <input formControlName=''>
  </div>
  <div formArrayName=''>
      <input formControlName='{{index}}' 
        *ngFor='let item of items; index = index'>
  </div>

</form>

Useful Blocks

-- Get Form Items
JSON.stringify(myForm.value)

Useful Links

               
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          AngularJS Cheat Sheet
          Angular 2 Http Cheat Sheet
          Angular Cheat Sheet

          More Cheat Sheets by Nathane2005

          Angular2 Pipes Cheat Sheet
          Angular 2 Http Cheat Sheet