I am currently facing a challenge with setting form controls using *ngFor over objects in an Array. The number of objects in the array can vary, sometimes resulting in only 1 object while other times multiple objects are present.
My specific issue revolves around creating form control names dynamically within the loop and setting form group validators in the component. Simply defining them as shown below causes a problem - if there is only one object, the form remains invalid due to the absence of another formControlName that does not exist.
For instance, if the first object named "Days" is missing from the list, "Days" still exists in this.form and appears in controls:
Array:
indicators = [
{name:"Days",data:[250,1]},
{name:"Multiply Average",data:[3,.25,1]}
],
Component:
ngOnInit() {
this.form = this._fb.group({
"Multiply Average":['', Validators.compose([
Validators.required
])],
"Days":['', Validators.compose([
Validators.required
])],
});
};
Template:
<span
*ngFor="let i of indicators">
{{i.name}}:
<md-slider
formControlName={{i.name}}
color="primary"
[max]=i.data[0]
[thumb-label]="true"
[step]=i.data[1]
[min]=i.data[2]>
</md-slider>
</span>
If anyone has solutions or suggestions on how to address this dilemma, I would greatly appreciate any help provided.