引入表单组/表单建立/及验证相关类import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";
html
const form = new FormGroup({ // 域: (默认值,验证) uid: new FormControl('默认值', Validators.minLength(2)), pwd: new FormControl(''), pwdC: new FormControl(''), }, // 要验证多个表单控件并返回错误对象, 则: (fg)=>{ return fg.get('pwd').value === fg.get('pwdC').value ? null : {'mismatch': true} }); // 动态为表单添加控件 this.form.addControl('text',new FormControl(''))
public form: FormGroup this.form = this.formBuilder.group({ text: ["", [Validators.pattern(/^(.{0,50}\n)*[^\n]{0,50}$/)]], parent: [''], _id: [''] })
public uid: FormControl = new FormControl('默认值', Validators.minLength(2)) public form: FormGroup = { uid: this.uid } // 一些简单的表单交互只使用 FormControl 也是能够的, 比 ngModel 更方便. // 经常使用的操做: this.uid.setValue('aaa') // 赋值 this.uid.value // 取值 this.uid.valueChanges.debounceTime(200).subscribe(r=>{ }) // 订阅值的变更 thiss.uid.valid // 验证经过? thiss.uid.dirty // 脏了? 改动过 // ....
<!--[FormGroup] 指定FormGroup--> <form [formGroup]="form" (submit)="save()"> <!--<md-spinner *ngIf="form.disabled"></md-spinner>--> <!--formControlName 指定控件--> <inpout placeholder="输入" formControlName="text"></input> <button [disabled]="form.invalid || !form.dirty || form.untouched || form.disabled">保存</button> </form>
// 获取指定控件 this.form.get('text') // 启用并单 this.form.enable() // 禁用表单 this.form.disable() // 重置表单 this.form.reset() // 给控件赋值 this.form.setValue({ Key:value }) // 从表单取值 this.form.getRawValue() // 表单验证错误 this.form.errors