在Angular2中形成两个基本对象是Control
和ControlGroup
。
控制用户输入 Control
一个控制
表示一个输入字段(ngFormControl)
一个控制可以绑定到一个input元素,并采取3个参数(所有可选); 默认值,验证程序和异步验证。
import {Component} from '@angular/core'; import {Control} from '@angular/common'; import 'rxjs/Rx'; @Component({ selector: 'my-app', template: ` <div> <h2>ngFormControl</h2> <input type="text" [ngFormControl]="term"/> </div> ` }) export class App { public term = new Control(); constructor(){ this.term.valueChanges .debounceTime() .distinctUntilChanged() .subscribe(data=>conosle.log(data)) } }
debounceTime(400) 延时400ms输出
distinctUntilChanged() 直到停止键盘输入触发
subscribe() 监控输入框值得变化
控制组
大多数表单都有多个字段,所以我们需要一种方法来管理多个控制,我们使用Angular2的“FormBuilder”类多个控制结合起来。
import {Component , ViewChild ,ElementRef } from '@angular/core'; import {FORM_PROVIDERS, FormBuilder, Validators ,Control} from '@angular/common'; import 'rxjs/Rx'; @Component({ template :` <div style="padding-top: 10rem;"> <form [ngFormModel]="userForm" (submit)="saveUser()"> <ul> <li><input type="text" [ngFormControl]="term"/> {{term.value}}</li> <li><input type="text" [ngFormControl]="email"/> {{email.value}}</li> </ul> <button type="submit" [disabled]="!userForm.valid">Submit</button> </form> </div> ` }) export class FormComponent { public userForm: any; public term = new Control('',Validators.required); public email = new Control('',Validators.required) constructor(public formBuilder: FormBuilder){ this.userForm = this.formBuilder.group({ term : this.term, email : this.email }) this.term.valueChanges .debounceTime() .distinctUntilChanged() .subscribe(data=> console.log(this.userForm.valid)) } saveUser() { if (this.userForm.dirty && this.userForm.valid) { alert(`email: ${this.userForm.value.email}`); alert(`email: ${this.userForm.value.email}`); } } }
上面的ControlGroup使用ngFormModel指令,绑定到您的应用中。
<form [ngFormModel]="userForm" (submit)="saveUser()">
内置表单验证
Angualr2提供了三种内置的验证:
- Required
- minLength
- maxLength
));
对应的Html是:
<li> <input type="text" [ngFormControl]="name"/> {{name.value}} <div *ngIf="!name.vaild"> <span *ngIf="name.errors.maxlength">您输入的字数不对</span> </div> </li>
自定义表单验证
class UsernameValidator { publick startsWithNumber(control){ )) ){ return { “startsWithNumber”: true }; } return null; } }
您可能会注意到一个奇怪的是,返回null实际上意味着验证是有效的。
我们可以在我们的控制使用上面的验证器
this.name = new Control('', UsernameValidator.startsWithNumber);
多重校验
Angular2提供了两种方法来验证程序,Validators.compose和Validators.composeAsync。
综合以上的:
validation.service.ts
import {Injectable} from '@angular/core' @Injectable() export class ValidationService { emailValidator(code){ if(code.value != ""){ if(/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(code.value)){ return null; }else{ return {'invalidEmailAddress': true }; } } } passwordValidator(code){ return new Promise((resolve, reject) => { setTimeout(() => { if (code.value == "David") { resolve({"usernameTaken": true}) } else { resolve(null); }; }, ); }); } }
form.component.ts
import {Component , ViewChild ,ElementRef } from '@angular/core'; import {FORM_PROVIDERS, FormBuilder, Validators ,Control} from '@angular/common'; import 'rxjs/Rx'; import {ValidationService} from './validation.service' @Component({ template :` <div style="padding-top: 10rem;"> <form [ngFormModel]="userForm" (submit)="saveUser()"> <ul> <li> <input type="text" [ngFormControl]="username"/> <div *ngIf="!username.valid"> <span *ngIf="username.errors.required"> 请输入用户名 </span> <span *ngIf="username.errors.minlength"> 用户名不能少于6位 </span> <span *ngIf="username.errors.maxlength"> 用户名不能大于10位 </span> </div> </li> <li> <input type="text" [ngFormControl]="password"/> <div *ngIf="!password.valid && !password.pending"> <span *ngIf="password.errors.required"> 请输入密码 </span> <p *ngIf="password.errors.usernameTaken">This username is taken</p> </div> </li> <li> <input type="text" [ngFormControl]="email"/> <div *ngIf="!email.valid"> <span *ngIf="email.errors.required"> 请输入邮箱地址 </span> <span *ngIf="email.errors.invalidEmailAddress"> 请输入正确的邮箱地址 </span> </div> </li> </ul> <button type="submit" [disabled]="!userForm.valid">Submit</button> </form> </div> `, providers : [ValidationService] }) export class FormComponent { public userForm: any; ),Validators.maxLength()])); public password = new Control('',Validators.compose([Validators.required]),this.validationService.passwordValidator) public email = new Control('',Validators.compose([Validators.required ,this.validationService.emailValidator])) constructor(public formBuilder: FormBuilder , public validationService:ValidationService ){ this.userForm = this.formBuilder.group({ username : this.username, password : this.password, email : this.email }) this.username.valueChanges .debounceTime() .distinctUntilChanged() .subscribe(data=> console.log(this.username.errors)) } saveUser() { console.log(this.userForm.valid); if (this.userForm.dirty && this.userForm.valid) { alert(`email: ${this.userForm.value.email}`); alert(`email: ${this.userForm.value.email}`); } } }