angular4 動態表單

angular 表單

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

使用FormBuilder建立表單

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
相關文章
相關標籤/搜索