[英]Angular Error : Type 'void' is not assignable to type 'AbstractControl'
I got an error when setting the default value of my FormControl, but it returns an error like this :设置 FormControl 的默认值时出现错误,但它返回如下错误:
error TS2322: Type 'void' is not assignable to type 'AbstractControl'错误 TS2322:类型“void”不可分配给类型“AbstractControl”
This is my .ts file :这是我的 .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"),
});
Help me to solve this.帮我解决这个问题。
FormControl.setValue()
returns a void
- which means it returns nothing. FormControl.setValue()
返回一个void
- 这意味着它不返回任何内容。
You're effectively trying to create an object with the following signature:您实际上是在尝试创建具有以下签名的对象:
{
username: void,
firstname: void,
...
}
Which is both meaningless and invalid for constructing a FormGroup
.这对于构造FormGroup
意义又无效。 FormGroup expects an object with the following signature in its constructor: FormGroup 需要一个在其构造函数中具有以下签名的对象:
{
[key: string]: FormControl
}
So something more like:所以更像是:
{
username: new FormControl(),
firstname: new FormControl(),
...
}
If you want to access the form controls programmatically, you could do this:如果要以编程方式访问表单控件,可以执行以下操作:
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,
...
});
You can use form builder:您可以使用表单构建器:
profileForm: FormGroup;
constructor(private _formBuilder: FormBuilder) {}
ngOnInit() {
this.profileForm = this._formBuilder.group({
username: [{ value: 'a' }],
...
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.