Angular2 Forms :Validations, ngControl, ngModel etc

36,965

Solution 1

Binding Form Controls to a Domain Model

Initialize the domain model within your component:

constructor(){
  this.student = new Student();
}

Use ngModel to bind to the form controls to a domain model with two-way model binding.

Name: <input [(ngModel)]="student.name" type="text">
Password:  <input [(ngModel)]="student.password" type="text">

When the button is clicked, pass the domain model as an argument:

<button type="button" (click)="addNewGroup(student)">Create</button>

Implement the addNewGroup method. To reset the form, update the domain model with a new model:

addNewGroup(student:Student) {
  alert('added ' + student.name);
  this.student = new Student();
}

Demo Plnkr

Adding Validators to the Form

To add form validation, add ngFormModel to the form element and add ngControl decorators to each input element (ngControl is syntactic sugar for [ngFormControl]="studentForm.controls['name']"):

<form [ngFormModel]="studentForm" />
   <input type="text" ngControl="name" />
   <input type="text" ngControl="password" />
</form>

The ngFormModel maps to a ControlGroup property of your component. Initialize the ControlGroup with a configuration object whose property names correspond to the values from the ngControl attributes:

constructor(fb: FormBuilder){
  this.student = new Student();
  this.studentForm = fb.group({
     'name': new Control(this.student.name, Validators.required),
     'password': new Control(this.student.password, Validators.required)
  });
}

In the above example, the built-in required validator is used to indicate that name and password are required fields. You can then check whether the entire form is valid using the valid property on the form model:

addNewGroup(student:Student) {
    if (this.studentForm.valid) {
      alert('added ' + student.name);
      this.student = new Student();
    }
    else {
      alert('form is not valid!');
    }
}

Demo Plnkr

Showing Validation Messages

If you want to bind to validation messages in the view, you can export the Control as a local template variable and access it's validation properties: valid, dirty, pending, pristine, and the errors object.

 <input ngControl="name" #name="ngForm" type="text">
 <span [hidden]="name.valid"><b>Required</b></span>

Demo Plnkr

If you want to create your own custom validator, create a method that returns a validation object whose boolean properties correspond to validation errors. For example, you can create a validator that ensures that the first letter of a password must be numeric:

interface ValidationResult {
 [key:string]:boolean;
}
class PasswordValidator {
 static startsWithNumber(control: Control): ValidationResult { 
   if ( control.value && control.value.length > 0){
     if (isNaN(control.value[0]))
      return { 'startsWithNumber': true };
   }

   return null;
 } 
}

Compose validators together into one validator and pass it to the Control constructor using the built-in Validators.compose:

this.studentForm = fb.group({
   'name': new Control(this.student.name, Validators.required),
   'password': new Control(this.student.password, Validators.compose([Validators.required,PasswordValidator.startsWithNumber])),
});

If you have multiple validators on the same Control, use the errors object to distinguish between them:

<input ngControl="password" #password="ngForm" />
<span [hidden]="!password.control.hasError('required')"><b>Required</b></span>
<span [hidden]="!password.control.hasError('startsWithNumber')"><b>Must start with number</b></span>

Demo Plnkr

Binding to Radio Button Lists

In Angular2, there is no built-in support yet to bind to radio button lists. Check this post to find out how to do this:

Angular2 - Radio Button Binding

Solution 2

UPADTED - ANGULAR2 RC4 FORMS

TL;DR;

After the release of angular2 RC Forms there are lot of changes have been made in angular2 forms. there are some of them are major breaking changes some of them are negligible, here are some key points for using angular2 forms.

Basically there are two ways to build forms in Angular 2, namely template-driven and model-driven. basic structure for using forms are as follows:-

  • run npm install @angular/forms --save
  • configure bootstrap method for your app as following:

    bootstrap(AppComponent, [
      disableDeprecatedForms(), // disable deprecated forms
      provideForms(), // enable new forms module
    ]);
    
  • use REACTIVE_FORM_DIRECTIVES to component directives to use forms functionality.

  • create Form variable of type FormGroup
  • Use Validators for validatiion purpose.

apart from this FormBuilder is not a mandatory to building model driven form, but it simplify the syntax. there are three basic syntax/method provided by formbuilder are:

  • group: construct a new form group.
  • array: construct a new form array.
  • control: construct a new form control.

These are the basic steps to use forms in angular2 RC.

Usefull resources for angular2 forms:

Live Demo for the same here

Working Demo for angular2 Forms

Share:
36,965
Pardeep Jain
Author by

Pardeep Jain

JavaScript developer | Contributor | Writer. | Angular ❤️ | I'm looking for projects to work on. Reach me out for any work here [email protected] Twitter | LinkedIn | YouTube | Facebook | Github | Medium | Quora Angular Community India | Ranked 1 as a contributor in India for Angular

Updated on June 05, 2020

Comments

  • Pardeep Jain
    Pardeep Jain almost 4 years

    Working on angular2 beta Forms. after alot of searching found nothing useful. hope here somebody help me.

    Basically i am bit confused how to use forms in angular2 in a proper manner (i.e using ngControl, ngFormControl etc). i have created one plnkr here

    http://plnkr.co/edit/fictP28Vqn74YqrwM1jW?p=preview

    here is my .html code:-

    <form class="form-horizontal" id='myForm' role="form" [ngFormModel]="CreateGroup">
    
      <div class="col-md-7">
    Name: <input type="text" id="name" placeholder="Name" class="form-control" ngControl="name">
      </div>
      <div class="col-md-7">
      Password:   <input type="text" id="password" placeholder="password" class="form-control" ngControl="password">
      </div>
    
      <div class="col-md-7">
        <input type="radio" name='type'>Btech
        <input type="radio" name='type'>Mtech
      </div>
    
      <div class="col-md-7">
        <input type="checkbox" >Math
        <input type="checkbox">English
        <input type="checkbox">Science
      </div>
      <br>
      <div class="col-md-7">
        <select #selectOption (change)='getValue(selectOption.value)' class='form-control'>
          <option value='1'>One Value</option>
          <option value='2'>two Value</option>
          <option value='3'>Three Value</option>
        </select>
      </div>
    </form>
    <button type="button" (click)="addNewGroup(CreateGroup.value)" class="btn btn-primary btn-lg"> Create </button>
    

    and .ts code is here:-

    CreateGroup: FormBuilder;
      constructor(fb: FormBuilder){
        console.log('form called');
    
        this.CreateGroup = fb.group({
                'name': new Control(),
                'password': new Control()
            })
      }
      addNewGroup(value) {
        console.log(value);
        document.getElementById("myForm").reset();
      }
    
      getValue(value){
        console.log(value);
      }
    

    i am unable to understand how to get values as object from complete form. my form include textboxes,checkboxes,radio and select options. now here are few of my questions.

    Q1:- How to get values of radio,checkbox,select using form in angular2. (i dont want to call change hook for select option as i have used in the plnkr).

    Q2:- as in the plnkr after submitting data form control has not been reset. Control of the form remains present but form seems reset. so how to reset the control of forms in angular2.

    Q3:- whats the best method to use validation in the forms (if anyone have plnkr showing validation please post it).

    i had read this article on forms but still not succesfull with radio checkboxes and select options.

    http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2

  • Pardeep Jain
    Pardeep Jain about 8 years
    Thank you so much for your time. i have't tried any of these methods you posted yet but i hope this will clear many points. But yes one thing more in your answer you have't posted anything about checkboxes and select options if you have any point related to these please update your answer. +1 for Great Explanations and providing plnkr, thnx again :)
  • Pardeep Jain
    Pardeep Jain about 8 years
    great work. but there is error occured after submitting second and third plnkr (Validation and error message plnkr). please will you remove it ?
  • pixelbits
    pixelbits about 8 years
    Yes, I noticed that too. It has to do with showing {{ form.valid }} for demo purposes. The error is "binding has changed since last time it was checked". I am thinking this is for the Angular team to fix. However, to fix it the demo, I just moved the binding to the bottom.
  • Paul Whelan
    Paul Whelan about 8 years
    beta6 I believe has binding to radio buttons github.com/angular/angular/blob/master/CHANGELOG.md]
  • Günter Zöchbauer
    Günter Zöchbauer over 7 years
    RC.5 was just released and this was changed :p
  • Pardeep Jain
    Pardeep Jain over 7 years
    ahh...so lets have a look at the new changes :p will again post new answer after learning something new :p