引入表單組/表單建立/及驗證相關類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