4.响应式表单重构

2018-03-04  本文已影响0人  Monee121

1.首先写数据模型
2,指令链接

<form [formGroup]="formModel" (submit)="onSubmit()">
  <div>用户名:<input type="text" name="username" formControlName="username"/></div>
  <div formGroupName="passwordsGroup">
     <div>密码:<input type="text" name="password" formControlName="password"/></div>
     <div>确认密码:<input type="text" name="confirmpass" formControlName="confirmpass"/></div>
  </div>
  <div>电话:<input type="text" name="mobile" formControlName="mobile"/></div>
  <div><input type="submit" value="提交"/></div>
</form>
export class ReactiveRegistComponent implements OnInit {

  formModel: FormGroup;
  constructor() {

    this.formModel = new FormGroup({
      username: new FormControl(),
      mobile: new FormControl(),

      passwordsGroup: new FormGroup({
         password: new FormControl(),
        confirmpass: new FormControl()
        }),

      password: new FormControl(),
      confirmpass: new FormControl()
    });
  }

  onSubmit() {
    console.log(this.formModel.value);
  }
  ngOnInit() {
  }

}

用FormBulider来配置一个表单模型比用new关键字实例化类,代码少,fb.group相当于new 了一个group,可以接受另外一个参数,校验,用一个数组实例化formcontrol实例,第一个元素初始值,校验方法,if的校验方法。多于三个,其他元素忽略。

export class ReactiveRegistComponent implements OnInit {
  formModel: FormGroup;
  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
     /* username: new FormControl(),*/
     username: [''],
      mobile: [''],
      passwordsGroup: fb.group({
         password: [''],
        confirmpass: ['']
        }),
      password: new FormControl(),
      confirmpass: new FormControl()
    });
  }
  onSubmit() {
    console.log(this.formModel.value);
  }
  ngOnInit() {
  }

}

上一篇 下一篇

猜你喜欢

热点阅读