Angular Error : Type 'void' is not assignable to type 'AbstractControl'

Angular Error : Type 'void' is not assignable to type 'AbstractControl'

我在设置我的 FormControl 的默认值时遇到了一个错误,但是 returns 出现了这样的错误 :

error TS2322: Type 'void' is not assignable to type 'AbstractControl'

这是我的 .ts 文件:

  profileForm  = new FormGroup({ 
    username   : new FormControl().setValue("a"),
    firstname  : new FormControl().setValue("a"),
    lastname   : new FormControl().setValue("a"),
    email      : new FormControl().setValue("a"),
    password   : new FormControl().setValue("a"),
  }); 

帮我解决一下。

FormControl.setValue() returns 一个 void - 这意味着它 returns 什么都没有。

您实际上是在尝试创建具有以下签名的对象:

{
  username: void,
  firstname: void,
  ...
}

对于构造FormGroup既无意义又无效。 FormGroup 需要一个在其构造函数中具有以下签名的对象:

{
  [key: string]: FormControl
}

所以更像是:

{
  username: new FormControl(),
  firstname: new FormControl(),
  ...
}

如果您想以编程方式访问表单控件,您可以这样做:

const formControls = {
  username: new FormControl('a'),
  firstname: new FormControl('a'),
  ...
};

// or this
formControls.username.setValue('a');
formControls.firstname.setValue('a');
// ... etc

profileForm = new FormGroup({
  username: formControls.username,
  firstname: formControls.firstname,
  ...
});

您可以使用表单生成器:

profileForm: FormGroup;

constructor(private _formBuilder: FormBuilder) {}

ngOnInit() {
        this.profileForm  = this._formBuilder.group({
            username: [{ value: 'a' }],
            ...
          }); 
    }