angular4 动态表单

发布时间:2019-06-04 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了angular4 动态表单脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Angular 表单

引入表单组/表单创建/及验证相关类
import { FormGroup, FormBuilder, Validators, FormControl } From "@angular/forms";

创建表单及验证

const form = new FormGroup({
  // 域: (默认值,验证)
  uid: new FormControl(@H_406_28@'默认值', 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

脚本宝典总结

以上是脚本宝典为你收集整理的angular4 动态表单全部内容,希望文章能够帮你解决angular4 动态表单所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。