angular4 动态表单

小鱼儿 2021-04-24 14:25 611阅读 0赞

angular 表单

引入表单组/表单创建/及验证相关类

  1. import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";

创建表单及验证

  1. const form = new FormGroup({
  2. // 域: (默认值,验证)
  3. uid: new FormControl('默认值', Validators.minLength(2)),
  4. pwd: new FormControl(''),
  5. pwdC: new FormControl(''),
  6. },
  7. // 要验证多个表单控件并返回错误对象, 则:
  8. (fg)=>{
  9. return fg.get('pwd').value === fg.get('pwdC').value ? null : {'mismatch': true}
  10. });
  11. // 动态为表单添加控件
  12. this.form.addControl('text',new FormControl(''))

使用FormBuilder创建表单

  1. public form: FormGroup
  2. this.form = this.formBuilder.group({
  3. text: ["", [Validators.pattern(/^(.{0,50}\n)*[^\n]{0,50}$/)]],
  4. parent: [''],
  5. _id: ['']
  6. })

实际上这样更直观

  1. public uid: FormControl = new FormControl('默认值', Validators.minLength(2))
  2. public form: FormGroup = {
  3. uid: this.uid
  4. }
  5. // 一些简单的表单交互只使用 FormControl 也是可以的, 比 ngModel 更方便.
  6. // 常用的操作:
  7. this.uid.setValue('aaa') // 赋值
  8. this.uid.value // 取值
  9. this.uid.valueChanges.debounceTime(200).subscribe(r=>{ }) // 订阅值的变动
  10. thiss.uid.valid // 验证通过?
  11. thiss.uid.dirty // 脏了? 改动过
  12. // ....

模板

  1. <!--[FormGroup] 指定FormGroup-->
  2. <form [formGroup]="form" (submit)="save()">
  3. <!--<md-spinner *ngIf="form.disabled"></md-spinner>-->
  4. <!--formControlName 指定控件-->
  5. <inpout placeholder="输入" formControlName="text"></input>
  6. <button [disabled]="form.invalid || !form.dirty || form.untouched || form.disabled">保存</button>
  7. </form>

常用

  1. // 获取指定控件
  2. this.form.get('text')
  3. // 启用并单
  4. this.form.enable()
  5. // 禁用表单
  6. this.form.disable()
  7. // 重置表单
  8. this.form.reset()
  9. // 给控件赋值
  10. this.form.setValue({
  11. Key:value
  12. })
  13. // 从表单取值
  14. this.form.getRawValue()
  15. // 表单验证错误
  16. this.form.errors

发表评论

表情:
评论列表 (有 0 条评论,611人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Angular4

    Angular4的表单分为两种,一个是模板式表单,另一种是响应式表单。 首先先讲一下数据模型:数据模型不是任意一种对象,是一种用于存储表单数据的数据结构。 模板式表单

    相关 动态

    项目中往往需要动态的创建一个表单,或者添加一个新的数据模板,这时候因为需要在运行时动态的创建表以及动态的维护表字段甚至表关系,本篇博客,做一个简单的示例 数据库表 DD