Angular 2 Ng Control

ngControl directive ensure the tracking of: the state change and validation of data within all form elements (html form element like input). We can call an element a control. Control = Element .

ngControl is used internally by all forms.

ngControl adds some CSS classes to the element. (To adjust the appearance of the elements: show message errors…)

angular 2 ngcontrol example 1
angular 2 ngcontrol example 1

In this example show us how to use ngControl inside an element in a form.

ngControl used as an attribute.

 

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.

 

Let’s create our example: angular-2-ng-control.component.ts

ngControl needs a unique identifier of the current element. (We can do it by declaring a local variable inside the element: #exampleNgControl=”ngForm”)


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

/*this example shows how to use ngControl*/
@Component({
    selector: 'example-ng-control',
    template:`

<h2>Angular 2 ngControl Example</h2>


<form (ngSubmit)="onSubmit(exampleNgControlForm.value)" #exampleNgControlForm="ngForm">

<div class="form-group">
                    <label class="col-xs-2 control-label">Empty me : </label>

<div class="col-xs-10">
                        <input type="text" style="width: 300px" class="form-control" required [(ngModel)]="exampleElemenValue" ngControl="exampleElemenValue" #exampleNgControl="ngForm" >

<div [hidden]="exampleNgControl.valid || exampleNgControl.pristine" class="alert alert-danger">
                         The current element is empty. Value required !
                         </div>

                         value is : {{exampleElemenValue}}
                    </div>

                </div>


                </form>


    `,
    directives: [CORE_DIRECTIVES,FORM_DIRECTIVES]
})
export class ExampleNgControlComponent {
    exampleElemenValue:string ="default text";

    constructor (){
      //this.exampleElemenValue="constructor text"; //if you uncomment this the default value will be 'constructor text' : )
    }

}

angular 2 ngcontrol example 2
angular 2 ngcontrol example 2