Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues before reaching this point).
Below are my attempts:
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,]),
})
//shortened for example purposes
...
Error in Logic
ngOnInit(): void {
if (someLogic) {
Object.keys(this.exampleForm.controls).forEach((key) => {
this.exampleForm.controls[key].setValue("some value");
//other logic here using key
});
}
}
Error Received:
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>;
Solutions Attempted:
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
});
}
//resolved previous error but encountered a new one stating Type 'null' cannot be used as an index type.
It is essential for me to use the forEach block on these groups for reasons other than just setting values, thus patchValue() is not an appropriate solution.