Great job! I have implemented the code as you suggested, and it is working flawlessly. You can check it out and run some tests on it by visiting STACKBLITZ.
Using a FormGroup with an Angular ReactiveForm is indeed the way to go:
- Make sure to import the ReactiveFormsModule in your module (such as AppModule) where you want to use the form (like AppComponent):
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
- In your component, define and "build" your form dynamically for each row of your table:
import { Component, OnInit, VERSION } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
form: FormGroup;
members = [
{
dataLimit: 'Package 1: Voice',
value: 0,
uom: 'Minutes',
},
{
dataLimit: 'Package 2: SMS',
value: 0,
uom: 'Units',
},
];
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
const myFields = this.buildFormFieldsFormGroup();
console.log('myFields: ', myFields);
this.form = myFields;
}
private buildFormFieldsFormGroup(): FormGroup {
const membersLength = this.members.length;
let response: FormGroup = this.fb.group({ dummy: ['', []] });
for (let i = 0; i < membersLength; i++) {
response.addControl(`field${i}`, new FormControl());
}
console.log('response: ', response);
return response;
}
}
- Add the form and formControls to your HTML:
<div>
<form [formGroup]="form">
<table>
<thead>
<tr>
<th></th>
<th>Value</th>
<th>Unit of Mesure</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let member of members, let i=index">
<td>{{ member.dataLimit }}</td>
<td><input type="text" value="{{ member.value }}" formControlName="field{{i}}" /></td>
<td>{{ member.uom }}</td>
</tr>
</tbody>
</table>
</form>
</div>
- To verify that everything is functioning correctly, add this at the end of your HTML:
FORM VALUE: {{ form.value | json }}
After entering values into the table, you will see them reflected in the corresponding fields, just like in this screenshot:
https://i.sstatic.net/Useke.png
You'll find the first row's value in the form under its "field0" field, and so forth...
(NOTE: The 'dummy' field remains in the form for now as a placeholder. In the future, I plan to refine the code to remove this unnecessary element. However, currently, it does not impact the functionality of the form.)