Angular2笔记4-Form验证 Posted on 2016-07-12 | In Angular2入门 | 在ng2 form中两个基本的对象是Control 和 ControlGroup.一个Control代表着一个input字段(这是一个ng2表单的最小单位)Control 封装了该字段的值,状态.. Control和ControlGroup1<input type="text" ng-control="name" /> 12345678910111213141516171819202122232425// create a new Control with the value "Nate"var nameControl = new Control("Nate");var name = nameControl.value; // -> Nate// now we can query this control for certain values:nameControl.errors // -> StringMap<string, any> of errorsnameControl.dirty // -> falsenameControl.valid // -> truevar personInfo = new ControlGroup({ firstName: new Control("Nate"), lastName: new Control("Murray"), zip: new Control("90210")})// now we can query this control group for certain values, which have sensiblepersonInfo.value; // -> {// firstName: "Nate",// lastName: "Murray",// zip: "90210"// }// values depending on the children Control's values:personInfo.errors // -> StringMap<string, any> of errorspersonInfo.dirty // -> falsepersonInfo.valid // -> true 最简单的form12//引入导出的类import {DemoFormSkuBuilder} from './forms/demo_form_sku_with_builder'; 1234567891011121314151617181920212223@Component({ selector: 'demo-form-sku', template: ` <div class="ui raised segment"> <h2 class="ui header">Demo Form: Sku</h2> <form #f="ngForm" (ngSubmit)="onSubmit(f.value)" class="ui form"> <div class="field"> <label for="skuInput">SKU</label> <input type="text" id="skuInput" placeholder="SKU" name="sku" ngModel> </div> <button type="submit" class="ui button">Submit</button> </form> </div> `})export class DemoFormSku { onSubmit(form: any): void { console.log('you submitted value:', form); }} 自定义验证form123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566function skuValidator(control: FormControl): { [s: string]: boolean } { if (!control.value.match(/^123/)) { return {invalidSku: true};//新增的error类型 }}// sku 相当于是一个new Control("");//sku.errors, sku.dirty, sku.valid 这些Control的属性//用*ngIf控制UI@Component({ selector: 'demo-form-with-custom-validations', directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES], template: ` <div class="ui raised segment"> <h2 class="ui header">Demo Form: with custom validations</h2> <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="ui form"> <div class="field" [class.error]="!sku.valid && sku.touched"> <label for="skuInput">SKU</label> <input type="text" id="skuInput" placeholder="SKU" [formControl]="sku"> <div *ngIf="!sku.valid" class="ui error message">SKU is invalid</div> <div *ngIf="sku.hasError('required')" class="ui error message">SKU is required</div> <div *ngIf="sku.hasError('invalidSku')" class="ui error message">SKU must begin with <tt>123</tt></div> </div> <div *ngIf="!myForm.valid" class="ui error message">Form is invalid</div> <button type="submit" class="ui button">Submit</button> </form> </div> `})export class DemoFormWithCustomValidations { myForm: FormGroup;//表单里[formGroup]="myForm" sku: AbstractControl; constructor(fb: FormBuilder) { //Form默认是一个ControlGroup this.myForm = fb.group({ //[formControl]="sku" //赋值可以用'sku':['ABC123'] //Validators.compose用于追加一个验证, 不然'sku': ['', Validators.required]只会保留一个 'sku': ['', Validators.compose([Validators.required, skuValidator])] }); this.sku = this.myForm.controls['sku']; //监听值的变化事件 this.sku.valueChanges.subscribe( (value: string) => { console.log('sku changed to:', value); } ); this.myForm.valueChanges.subscribe( (form: any) => { console.log('form changed to:', form); } ); } onSubmit(value: string): void { console.log('you submitted value: ', value); }}