Angular Ng Model Example

ngModel binds a model (where data is stored) to a form control (an element like <input>) in angular 2.

ngModel is the mechanism used to ensure the two-way data binding in angular 2.

angular 2 ng model
angular 2 ng model

Let’s write our demo : ngModel

angular 2 ng model example
angular 2 ng model example
  • You can find the Code Source at the end of this tutorial.

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.

Step 1

The first file is : angular-2-ng-model.component.ts

It contains contains the code where we use the ngModel.

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

/*this example show us how to use ngModel*/
@Component({
    selector: 'example-ng-model',
    template:`
                <h2>Angular 2 ngModel Example</h2>
                <div class="form-group">
                    <label class="col-xs-2 control-label">Say Hello to NgModel : </label>
                    <div class="col-xs-10">
                        <input type="text" style="width: 300px" class="form-control"
                               [(ngModel)]="exampleNgModel"
                        >
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-xs-2 control-label">Your Hello : </label>
                    <div class="col-xs-10">
                        {{exampleNgModel}}
                    </div>
                </div>
    `
})
export class ExampleNgModelComponent {
    exampleNgModel:string ="Good";
    constructor (){
        //this.exampleNgModel="Great"; //if you uncomment this the default value will be Great : )
    }
}

Step 2

We create the app (we call our angular-2-ng-model.component ) with tihs syntax :

<example-ng-model>loading...</example-ng-model>
/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component} from 'angular2/core';
import {ExampleNgModelComponent} from "./angular-2-ng-model.component";

@Component({
    selector: 'my-app',
    template: `
                <example-ng-model>loading...</example-ng-model>
               `,
    directives: [ExampleNgModelComponent]
})
export class ExampleNgModelAppComponent {

}

Step 3

We bootsrap our application to see the demo in action.

import {ExampleNgModelAppComponent} from "./core/angular2common/NgModel/ng-model-app.component";

bootstrap(ExampleNgModelAppComponent);

Download – Angular 2 ng model – Code Source