I am using Angular v14 and the upgrading my formGroups to strictly typed. I have a block of logic that if executed, iterates through all the controls of a FormGroup and does something – this part isn’t important as I can’t even get to this part
Here is what I have tried:
Form Setup
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
...
Broken Logic Here
ngOnInit(): void {
if (someLogic) {
Object.keys(this.exampleForm.controls).forEach((key) => {
this.exampleForm.controls[key].setValue("some value");
//other logic here using key
});
}
}
Error i receive:
Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ q1: FormControl<string | null>; q2: FormControl<string | null>; q3: FormControl<string | null>;
What I have tried:
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.
Also I need to use the forEach block on these groups for other reasons than just setting a value so patchValue() won’t suffice.
>Solution :
I think the problem is that the form has the keys q1, q2, q3, etc. but you are trying to index it with a string. Try this:
for (const [key, control] of Object.entries(this.exampleForm.controls)) {
control.setValue('some value');
// ...
}
Since the compiler knows that this.exampleForm.controls looks like this:
{
q1: ...,
q2: ...,
q3: ...
}
Only keys in the type 'q1' | 'q2' | 'q3' are guaranteed to have a value when used to index it.