Angular2 / 4/5 - Reactive Forms,你应该使用AbstractControl还是FormControl?

时间:2018-01-14 17:55:46

标签: angular forms reactive

在我参与的不同项目中,我已经看到了以下两种不同的方法来构建反应形式。推荐哪种方式?

使用AbstractControl

  public form: FormGroup;
  public fb: FormBuilder;
  public to: AbstractControl;
  public subject: AbstractControl;
  public body: AbstractControl;

  private ngOnInit() {
    this.form = this.fb.group({
      'to': ['', Validators.compose([Validators.required, emailValidator])],
      'subject': ['', Validators.compose([Validators.required])],
      'body': ['', Validators.compose([Validators.required])],
    });
    this.to = this.form.controls['to'];
    this.subject = this.form.controls['subject'];
    this.body = this.form.controls['body'];
  }  

使用FormControl

  public form: FormGroup;
  public fb: FormBuilder;
  public to: FormControl;
  public subject: FormControl;
  public body: FormControl;

  private ngOnInit() {
    this.form = this.fb.group({
      'to': ['', Validators.compose([Validators.required, emailValidator])],
      'subject': ['', Validators.compose([Validators.required])],
      'body': ['', Validators.compose([Validators.required])],
    });
    this.to = new FormControl['to'];
    this.subject = new FormControl['subject'];
    this.body = new FormControl['body'];
  } 

我还发现docs here表示不应该直接实例化AbstractControl,那么这意味着方法1不是推荐的方法吗?

1 个答案:

答案 0 :(得分:2)

AbstractControl是大多数表单控件的基类。根据文档,您应该使用子类 - FormControl - 来实例化表单控件,主要是您获取每个ui对象的值和验证器状态。

const body = new FormControl({value: 'n/a', disabled: true});
console.log(body.status); // disabled
console.log(body.value);  // n/a