Angular2 FORM with controls and validation.
After a lot searching i concluded that using ngModel is best to get values from form. by using same it is easier to clear to controls of the forms. and validations gets easy. and used ngControl
for checking validations.
here is my working code for the form.
<form class="form-horizontal" id='myForm' role="form" [ngFormModel]="CreateGroup">
<div class="col-md-7">
Name: <input type="text" [(ngModel)]='demoInfo.name' class="form-control" ngControl='name'>
</div>
<div class="col-md-7">
Password: <input type="password" [(ngModel)]='demoInfo.password' class="form-control" ngControl='password'>
</div>
<div class="col-md-7">
<input type="radio" name='type' (click)='demoInfo.radio="Btech"' [checked]="'Btech' === demoInfo.radio">Btech
<input type="radio" name='type' (click)='demoInfo.radio="Mtech"' [checked]="'Mtech' === demoInfo.radio">Mtech
</div>
<div class="col-md-7">
<select #selectOption (change)='demoInfo.select=selectOption.value' class='form-control' ngControl='select'>
<option> select</option>
<option value='One' [selected]="demoInfo.select==='One'">One Value</option>
<option value='Two' [selected]="demoInfo.select==='Two'">two Value</option>
<option value='Three' [selected]="demoInfo.select==='Three'">Three Value</option>
</select>
</div>
</form>
<br>
<div class='text-center'>
<button type="button" [disabled]='!CreateGroup.valid' (click)="addNewGroup(demoInfo)" class="btn btn-primary">Create</button>
</div>
and code for the class side is here...
import {Component} from 'angular2/core';
import {CORE_DIRECTIVES, NgClass, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder, Validators} from 'angular2/common';
class DemoInfo{
name:string;
password: string;
radio: any;
select: any;
}
@Component({
selector: 'my-app',
templateUrl: 'mytemplate.html',
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class AppComponent {
CreateGroup: FormBuilder;
demoInfo: DemoInfo;
constructor(fb: FormBuilder){
this.demoInfo= new DemoInfo();
this.CreateGroup = fb.group({
'name': new Control(this.demoInfo.name, Validators.required),
'password': new Control(this.demoInfo.password, Validators.required),
'select': new Control(this.demoInfo.select, Validators.required)
})
}
addNewGroup(demoInfo:demoInfo) {
console.log(demoInfo, 'whole object');
this.demoInfo= new DemoInfo();
}
}
refer this for working plunkr here
.
see also -