I am currently developing an Angular application that utilizes reactive forms. I need to retrieve the values of dynamically created fields within a form group. Here is the code I have implemented:
this.formSaisieSecondary = this.fb.group({
options: this.fb.array([])
});
newOption(): FormGroup {
return this.fb.group({
date: ['', Validators.required],
cargoA: ['', Validators.required],
cargoB: ['', Validators.required],
cargoC: ['', Validators.required],
cargoD: ['', Validators.required],
cargoE: ['', Validators.required],
unite: [this.unite, Validators.required],
siloA: ['silo1', Validators.required],
siloB: ['silo2', Validators.required],
siloC: ['silo3', Validators.required],
siloD: ['silo4', Validators.required],
siloE: ['silo5', Validators.required],
comment: ['']
})
}
options(): FormArray {
return this.formSaisie.get("options") as FormArray;
}
AddOption() {
this.options().push(this.newOption());
}
Here is the corresponding HTML code:
<form [formGroup]="formSaisie">
<div formArrayName="options">
<div class="row mb-5" style="height: 23px;" *ngFor="let option of options().controls; let i = index" [formGroupName]="i">
<div class="col-md-1">
<input formControlName="date" type="text" formControlName="date" hidden [(ngModel)]="listDate[i]">
<p>{{listDate[i]}}</p>
</div>
<div class="col-md-2">
<mat-form-field class="inputGridItem" appearance="fill">
<mat-label>Cargaison</mat-label>
<mat-select formControlName="cargoA" required>
<mat-option *ngFor="let cargo of dataEx" [value]="cargo.cargoId">
{{cargo.vessel + " " + cargo.externalId}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
.............
The code was inspired by a similar approach found here.
My question pertains to how I can both retrieve and set values for the form fields. For example, to retrieve a value, I can do the following:
let value = this.formSaisie.value.options[0];
value.cargoA;
However, I am unsure of how to set a value for a field.