I have some dynamic input fields and I want to add them to my form group.
This is what I already have:
<div *ngFor="let section of sections">
<p>
<mat-form-field>
<mat-label>Title of Section</mat-label>
<input id="title-of-section-' section" #titleOfSection matInput type="text" value="Section 1" placeholder="E.g. Basic Package" [formControlName]="'title-of-section-' section">
</mat-form-field>
</p>
...
formMain = this.fb.group({
});
this.formMain.addControl(`title-of-section-${amountOfServices}`, new FormControl(''));
amountOfServices
is a increased number. So the controls could be:
- title-of-section-0
- title-of-section-1
- title-of-section-2
Well, that works fine but instead of that, I would like to have them all in an array, using FormArray
.
So I changed my code to this:
formMain = this.fb.group({
titleOfSection: new FormArray([])
});
const titleOfSection = this.formMain.get('titleOfSection') as FormArray;
titleOfSection.push(new FormControl());
That works fine as well. So now I have an array. But my problem is the HTML. I know that I could do something like this:
<div formArrayName="titleOfSection">
<ng-container *ngFor="let field of getItems().controls">
<input type="text" [formControl]="$any(field)" value="foo">
</ng-container>
</div>
getItems(): FormArray {
return this.formMain.get('titleOfSection') as FormArray;
}
The reason why I don't want it that way, is because I need my current loop (see code above), which is *ngFor="let section of sections"
since I need section
also for the rest of my code.
So my question is, can I keep my current for
loop but change [formControlName]="'title-of-section-' section"
to something like [formControl]="'titleOfSection[section]"
?
The value of sections
is the same as titleOfSection.value.length
.
CodePudding user response:
The reason why I don't want it that way, is because I need my current loop (see code above), which is *ngFor="let section of sections" since I need section also for the rest of my code.
In this case you could keep this code:
<div formArrayName="titleOfSection">
<ng-container *ngFor="let field of getItems().controls">
<input type="text" [formControl]="$any(field)" value="foo">
</ng-container>
</div>
Remove your *ngFor="let section of sections"
and use the above instead. And when you want to access the section
object you could do field.value
.
If that is not to your liking, you could do:
<ng-container *ngFor="let field of getItems().controls; let index = i">
{{ sections[i].something }}
</ng-container>
Since the indices in the FormArray
correspond to the ones in the sections
array, you could capture that by using let index = i
in the *ngFor
of the FormArray controls.