Angular 2


Angular 2 Forms Update All Versions

2.0.0-rc.0
2.0.0-rc.1
2.0.0-rc.2
2.0.0-rc.3
2.0.0-rc.4
2.0.0-rc.5
2.0.0-rc.6
2.0.0-rc.7
2.0.0
2.0.1
2.0.2
2.1.0
2.2.0
2.3.0
2.4.1

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 8
    import { Component } from '@angular/core';
    import { Router , ROUTER_DIRECTIVES} from '@angular/router';
    import { NgForm }    from '@angular/forms';
    
    @Component({
        selector: 'login',
        template: `
    <h2>Login</h2>
    <form #f="ngForm" (ngSubmit)="login(f.value,f.valid)" novalidate>
        <div>
            <label>Username</label>
            <input type="text" [(ngModel)]="username" placeholder="enter username" required>
        </div>
        <div>
            <label>Password</label>
            <input type="password" name="password" [(ngModel)]="password" placeholder="enter password" required>
        </div>
        <input class="btn-primary" type="submit" value="Login">
    </form>`
       //For long form we can use **templateUrl** instead of template
    })
    
    export class LoginComponent{
    
        constructor(private router : Router){ }
    
        login (formValue: any, valid: boolean){
            console.log(formValue);
            
            if(valid){
                console.log(valid);
            }
        }    
    }
    
  • 6

    For live demo click..

    App index ts

    import {bootstrap} from '@angular/platform-browser-dynamic';
    import {MyForm} from './my-form.component.ts';
    
    bootstrap(MyForm);
    

    Custom validator

    import {Control} from @'angular/common';
    
    export class CustomValidators {
      static emailFormat(control: Control): [[key: string]: boolean] {
        let pattern:RegExp = /\S+@\S+\.\S+/;
        return pattern.test(control.value) ? null : {"emailFormat": true};
      }
    }
    

    Form Components ts

    import {Component} from '@angular/core';
    import {FORM_DIRECTIVES, NgForm, FormBuilder, Control, ControlGroup, Validators} from '@angular/common';
    import {CustomValidators} from './custom-validators';
    
    @Component({
      selector: 'my-form',
      templateUrl: 'app/my-form.component.html',
      directives: [FORM_DIRECTIVES],
      styleUrls: ['styles.css']
    })
    export class MyForm {
      email: Control;
      password: Control;
      group: ControlGroup;
      
      constructor(builder: FormBuilder) {
        this.email = new Control('', 
          Validators.compose([Validators.required, CustomValidators.emailFormat])
        );
        
        this.password = new Control('',
          Validators.compose([Validators.required, Validators.minLength(4)])
        );
        
        this.group = builder.group({
          email: this.email,
          password: this.password
        });
      }
      
      onSubmit() {
        console.log(this.group.value);
      }
    }
    

    Form Components HTML

    <form [ngFormModel]="group" (ngSubmit)="onSubmit()" novalidate>
    
      <div>
        <label for="email">Email:</label>
        <input type="email" id="email" [ngFormControl]="email">
        
        <ul *ngIf="email.dirty && !email.valid">
          <li *ngIf="email.hasError('required')">An email is required</li>
        </ul>
      </div>
    
      <div>
        <label for="password">Password:</label>
        <input type="password" id="password" [ngFormControl]="password">
        
        <ul *ngIf="password.dirty && !password.valid">
          <li *ngIf="password.hasError('required')">A password is required</li>
          <li *ngIf="password.hasError('minlength')">A password needs to have at least 4 characterss</li>
        </ul>
      </div>
    
      <button type="submit">Register</button>
    
    </form>
    
  • 4

    The below examples use the new form API introduced in RC3.

    pw-change.template.html

    <form class="container" [formGroup]="pwChangeForm">
        <label for="current">Current Password</label>
        <input id="current" formControlName="current" type="password" required><br />
    
        <label for="newPW">New Password</label>
        <input id="newPW" formControlName="newPW" type="password" required><br/>
        <div *ngIf="newPW.touched && newPW.newIsNotOld">
            New password can't be the same as current password.
        </div>
    
        <label for="confirm">Confirm new password</label>
        <input id="confirm" formControlName="confirm" type="password" required><br />
        <div *ngIf="confirm.touched && confirm.errors.newMatchesConfirm">
            The confirmation does not match.
        </div>
    
        <button type="submit">Submit</button>
    </form>
    

    pw-change.component.ts

    import {Component} from '@angular/core'
    import {REACTIVE_FORM_DIRECTIVES, FormBuilder, AbstractControl, FormGroup, 
        Validators} from '@angular/forms'
    import {PWChangeValidators} from './pw-validators'
    
    @Component({
        moduleId: module.id
        selector: 'pw-change-form',
        templateUrl: `./pw-change.template.html`,
        directives: [REACTIVE_FORM_DIRECTIVES]
    })
    
    export class PWChangeFormComponent {
        pwChangeForm: FormGroup;
    
        // Properties that store paths to FormControls makes our template less verbose
        current: AbstractControl;
        newPW: AbstractControl;
        confirm: AbstractControl;
    
        constructor(private fb: FormBuilder) { }
        ngOnInit() {
            this.pwChangeForm = this.fb.group({
                current: ['', Validators.required],
                newPW: ['', Validators.required],
                confirm: ['', Validators.required]
            }, {
                // Here we create validators to be used for the group as a whole
                validator: Validators.compose([
                    PWChangeValidators.newIsNotOld, 
                    PWChangeValidators.newMatchesConfirm
                ])
            );
            this.current = this.pwChangeForm.controls['current'];
            this.newPW = this.pwChangeForm.controls['newPW'];
            this.confirm = this.pwChangeForm.controls['confirm'];
        }
    }
    

    pw-validators.ts

    import {FormControl, FormGroup} from '@angular/forms'
    export class PWChangeValidators {
    
        static OldPasswordMustBeCorrect(control: FormControl) {
            var invalid = false;
            if (control.value != PWChangeValidators.oldPW)
                return { oldPasswordMustBeCorrect: true }
            return null;
        }
       
        // Our cross control validators are below
        // NOTE: They take in type FormGroup rather than FormControl 
        static newIsNotOld(group: FormGroup){
            var newPW = group.controls['newPW'];
            if(group.controls['current'].value == newPW.value)
                newPW.setErrors({ newIsNotOld: true });
            return null;
        }
    
        static newMatchesConfirm(group: FormGroup){
            var confirm = group.controls['confirm'];
            if(group.controls['newPW'].value !== confirm.value)
                confirm.setErrors({ newMatchesConfirm: true });
            return null;
        }
    }
    

    A gist including some bootstrap classes can be found here.

Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Angular 2 allow to access the ngForm instance by creating a local template variable. Angular 2 exposes directive instances like ngForm by specifying exportAs property of the directive metadata. Now, the advantage here is without much coding you can access the ngForm instance and use it to access submitted values or to check if all the fields are valid using properties (valid, submitted, value etc).

#f = ngForm (creates local template instance "f")

ngForm emits the event "ngSubmit" when it's submitted (Check @Output documentation for more details of event emitter)

(ngSubmit)= "login(f.value,f.submitted)"

"ngModel" creates a Form Control in combination with input "name" attribute.

<input type="text" [(ngModel)]="username" placeholder="enter username" required>

When form is submitted, f.value has the JSON object representing the submitted values.

{ username: 'Sachin', password: 'Welcome1' }

Still have a question about Angular 2 Forms Update? Ask Question

Topic Outline