我正在使用Angular v14,并将我的formGroups升级为严格类型。我有一个逻辑块,如果执行,它将遍历FormGroup的所有控件,并执行
有些东西——这部分并不重要,因为我甚至无法进入这部分
以下是我尝试过的:
表单设置
export interface ExampleForm{
q1 : FormControl<string | null>,
q2: FormControl<string | null>,
q3: FormControl<string | null>,
...
}
...
exampleForm= this.fb.group<ExampleForm>({
q1 : new FormControl('',[Validators.required,]),
q2 : new FormControl('',[Validators.required,]),
q3 : new FormControl('',[Validators.required,]),
})
//the form is much longer but shortening for example purposes
...
此处出现逻辑中断
ngOnInit(): void {
if (someLogic) {
Object.keys(this.exampleForm.controls).forEach((key) => {
this.exampleForm.controls[key].setValue("some value");
//other logic here using key
});
}
}
收到错误:
元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型“{q1:FormControl<string|null>;q2:FormControl<string| null<;q3:FormControl&llt;stringe|null>”;;
我所尝试的:
if (someLogic) {
Object.keys(this.exampleForm.controls).forEach((key:string) => {
this.exampleForm.controls[key].setValue("some value");
//other logic here using key
});
}
...
if (someLogic) {
Object.keys(this.exampleForm.controls).forEach((key : string | null) => {
this.exampleForm.controls[key].setValue("some value");
//other logic here using key
});
}
//with this the above error goes away but instead I get a new one saying Type 'null' cannot be used as an index type.
此外,由于其他原因,我需要在这些组上使用forEach块,而不仅仅是设置一个值
补丁值()
这还不够。