Angular2 响应式表单

参考资料
https://angular.cn/guide/reactive-forms#dynamic-controls-using-form-arrays

引入方法
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }
基础概念

1、FormControl
表单的最小单元,例如 input、select等

import { FormControl } from '@angular/forms';
name: FormControl;
this.name = new FormControl('初使姓名');

2、FormGroup
一组 FormControl 的合集,FormGroup相当于js中的对象,此时FormControl相当于js中的基础数据类型,如string、number等等

import { FormGroup } from '@angular/forms';
targetForm: FormGroup;  //  targetForm为name和age的合集
this.targetForm = new FormGroup({
  name: new FormControl('包子'),
  age: new FormControl(22)
})

注意: FormGroup和FormControl各自都有验证器,当FormGroup和FormControl的验证器都验证通过则表单才验证通过

3、FormArray
一组 FormControl 或者FormGroup或者FormArray或者三者混合的合集,相当于js中的数组

formArray: FormArray
this.formArray = this.fb.array([])
setInfo(data) {
  return this.fb.group({
      name: [data.name],
      age: [data.age]
    })
}
// 动态添加一组带有姓名和年龄的人的数据
const info = this.setInfo({name: 'Amy', age: '18'})
const infos = this.formArray as FormArray
infos.push(info)

// 页面渲染

注意:
FormControl、FormGroup和FormArray都继承了AbstractControl,所以它们都有AbstractControl所有的属性和方法
1、属性:valid、value、errors、touched、untouched 等等
2、方法:setValue、patchValue、reset等等

方法介绍

1、setValue
设置表单的值,结构必须与表单一致,否则会报错

this.targetForm.setValue({
   name: 'Tom',
   age: '16'
})

2、patchValue
更改表单的值,可以单个更新

this.targetForm.patchValue({
   age: '18'
})

3、reset
重置表单,将表单恢复至未被触发的状态(touched→untouched)

常用的表单验证器

1、FormGroup 整体验证器

this.targetForm = new FormGroup({
  name: new FormControl('包子'),
  age: new FormControl(22)
}, { validator: GroupValidator })

例子:注册用户时验证密码和确认密码是否相等

// 表单模型
this.registerForm = fb.group({
  phone: ['', Validators.compose([Validators.required,  phoneValidator])],
  password: ['', Validators.required],
  confirmPassword: ['', Validators.required]
}, {validator: isEqualPasswords('password', 'confirmPassword')})  // 全局验证器
 
// 验证器实现
 isEqualPasswords(passwordKey: string, confirmPasswordKey: string) {
  return (group: FormGroup): {[key: string]: any} => {
    const password = group.controls[passwordKey];
    const confirmPassword = group.controls[confirmPasswordKey];
    if (password.value !== confirmPassword.value) {
      return {
        InequalityPasswords: true
      };
    }
  }
}
// 页面渲染
密码和确认密码不一致!

2、FormArray 整体验证器

this.formArray = this.fb.array([], ArrayValidator)  // 第二个参数为整体验证器
表单适用情况

FormGroup 适用于明确的对象,是定义好的
FormArray 适用于需要动态的添加数组成员的情况

你可能感兴趣的:(Angular2 响应式表单)