Angular 2 Forms

 

Angular 2 form is a place where we give the user the possibility to enter some data (inputs).

angular 2 forms
angular 2 forms

If it’s your first time with Angular 2, Please check our hello world (step by step + npm and environment setup) tutorial here. to be able to run this example.

You can find the Code Source at the end of this tutorial.

 

next

try it Yourself, Live example

try angular 2 forms
try angular 2 forms

 

  • Inside a form we write our elements (or controls) like <input> <textarea> <radio>…
  • Angular 2 form allow the coordination of multiple user actions: watch data changes, data validation, errors detection.
  • Usually we use forms (e.g. ask a question, book a hotel …). In this tutorial we choose the green Car example.
  • We will create a form to allow a user to enter the name, color and number of doors for a given car.

 

let's build our form
let’s build our form

 

Let’s start our form:

  • We will use ngModel to allow the two way data binding (click on ngModel to read more about it).
  • We need ngControl to detect the data changes and to validate data (click on ngControl to read more about it).
  • We will see how to make use of CSS in our forms.
  • We will see how to show the error messages.

 

“This is a first example of forms we will see in other tutorials other ways to create forms with Angular 2.”

create the class greenCar
create the class greenCar

We create our class “GreenCar”: greencar.ts

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
export class GreenCar {
    constructor(
        public greenCarId: number,
        public greenCarName: string,
        public greenCarColor: string,
        public greenCarDoors: number
    ) {  }
}

We create this Class (greenCar) to be able later to create instances greenCar1, greenCar2 …

form component
form component

We create our form compoenent : angular-typescript-form.component.ts

Please read explanation in code source:

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component,EventEmitter,Output} from 'angular2/core';
import {CORE_DIRECTIVES,FORM_DIRECTIVES} from 'angular2/common';
import {GreenCar} from "./greencar";

// Our form component
@Component({
    selector: 'angular-typescript-form',
    templateUrl: 'app/angular-typescript-form.component.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]

})
export class FormExample {

    myCar = new GreenCar(1,'BMW Serie 1','Red',2); // this is our green car instance

    //the constructor is a good place for initialization (not big things)
    constructor(){
        console.log("Form Component Start");
    }

    submitted = false; //form not submitted : default
    data: string; //this variable contains our data

    //Show data in JSON format after form submit and set submitted to true
    onSubmit(data) {
        this.submitted = true;
        this.data = JSON.stringify(data, null, 2);
        console.log(this.data);
    }
}

create HTML template
create HTML template

We create our HTML template: angular-typescript-form.component.html

<h2>Angular 2 Forms</h2>
<form (ngSubmit)="onSubmit(carForm.value)" #carForm="ngForm">

    <div class="form-group">
        <label class="col-xs-2 control-label" for="greenCarName" >Green car name : </label>
        <div class="col-xs-10">
            <input type="text" style="width: 300px" class="form-control" required
                   [(ngModel)]="myCar.greenCarName"
                   ngControl="greenCarName"
                   #greenCarName="ngForm"

            >
            <div [hidden]="greenCarName.valid || greenCarName.pristine" class="alert alert-danger">
                The Name of green car is required !
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-xs-2 control-label" for="greenCarColor" >Green car color : </label>
        <div class="col-xs-10">
            <input type="text" style="width: 300px" class="form-control" required
                   [(ngModel)]="myCar.greenCarColor"
                   ngControl="greenCarColor"
                   #greenCarColor="ngForm"
            >
            <div [hidden]="greenCarColor.valid || greenCarColor.pristine" class="alert alert-danger">
                The Color of green car is required !
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-xs-2 control-label" for="greenCarDoors" >Green car doors : </label>
        <div class="col-xs-10">
            <input type="number" style="width: 300px" class="form-control" required
                   [(ngModel)]="myCar.greenCarDoors"
                   ngControl="greenCarDoors"
                   #greenCarDoors="ngForm"
            >
            <div [hidden]="greenCarDoors.valid || greenCarDoors.pristine" class="alert">
                The number of doors is required !
            </div>
        </div>
    </div>

    <div class="form-group">
        <div class="col-xs-12">
            <button type="submit" class="btn btn-default">Submit</button>
        </div>
    </div>
    <div class="form-group">
        <label class="col-xs-2 control-label" >Submitted Data : </label>
        <div class="col-xs-10">
            <div [hidden]="!submitted">
                <span>from angulartypescript.com</span>
                <textarea style="width: 300px" class="form-control" rows="6">{{data}}</textarea>
            </div>
            <div [hidden]="submitted">
                <span>Edit your Data then click Submit to get Data from : angulartypescript.com</span>
            </div>
        </div>
    </div>
</form> 
form main component
form main component

We create main Component (we will call our form Component here): general.component.ts

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component} from 'angular2/core';
import {FormExample} from "./angular-typescript-form.component";

@Component({
    selector: 'my-app',
    template: `
                <angular-typescript-form>loading...</angular-typescript-form>
               `,
    directives: [FormExample]
})
export class FormComponent {

}

As you may notice we call our Form Component with this syntax:

<angular-typescript-form>loading...</angular-typescript-form>

 

We car now bootsrap our application: main.ts

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {bootstrap} from 'angular2/platform/browser';
import {FormComponent} from "./general.component";


bootstrap(FormComponent);

  • We insert the Tag in index.html (to see the result)

 

use twitter bootstrap
use twitter bootstrap

 

To use twitter bootstrap css you need to install it with :

                       npm install bootstrap –save

 

 
<html>
<head>
    <title>Angular Typescript from angulartypescript.com</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 0. Css -->
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/angular2/bundles/router.dev.js"></script>
    <script src="node_modules/angular2/bundles/http.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
        System.import('app/main')
                .then(null, console.error.bind(console));
    </script>

    <link rel="stylesheet" href="src/css/app.css">
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>

 

error messages
error messages

 

This image illustrates the required control in our form, when an element (element or control it’s the same) is empty we can show a red alert.

angular typescript form angular 2 required
angular typescript form angular 2 required

Done !