It's a familiar routine. When controlling an object with ReactiveForms, the approach is consistent: create a FormGroup for single objects and a FormArray for arrays. For arrays representing objects, use a FormArray of FormGroup; for other arrays, simply use a FormArray.
The initial step involves defining the structure of your data. Considering that "levels" is an array, your data can be organized as follows:
{
"plannedProduction": 210468,
"factORLossTree": [
{
"skuid": "000000000034087070",
"skuDescription": "SUNLIGHT DESTINY HW PWD YELLOW 8X900G",
"productionOrderNo": "X49033251",
"category": "Fabric Cleaning",
"levels": [
{
"level1": "",
"level2": "",
"level3": ""
}
....
]
},
{
"skuid": "000000000067141695",
"skuDescription": "SUNLIGHT DESTINY YELLOW 24X170G",
"productionOrderNo": "X49039793",
"category": "Fabric Cleaning",
"levels": [
{
"level1": "",
"level2": "",
"level3": ""
}
....
]
},
....
]
}
For easy access to a FormArray in your code, utilize a getter (*) like this:
get lossFormArray() {
return this.orLosstreeForm.get('factORLossTree') as FormArray;
}
For accessing a nested FormArray within another FormArray, define another "getter" function where you need to provide the index of the formArray as an argument:
getLevels(index:number)
{
return this.lossFormArray.at(index).get('levels') as FormArray;
}
Additionally, you can implement an auxiliary function to retrieve the value of the formArray at a specific index, simplifying your .html file:
getItemValue(index:number)
{
return this.lossFormArray.at(index).value;
}
Lastly, include a function to create the FormGroup "level" successfully:
createLevel() {
return this.fb.group({
level1: [''],
level2: [''],
level3: [''],
});
When updating the formGroup by calling setData, make sure to adjust the function to accommodate the new FormGroup creation logic:
setData() {
const resp = {...}
// Rest of the existing logic here...
}
And the function createLevelItem should look as below:
createLevelItem(data) {
const formgrp = this.fb.group({
skuid: ['', Validators.required],
...
levels: this.fb.array([this.createLevel()]),
});
if (data !== null) {
formgrp.patchValue(data);
}
return formgrp;
}
This lengthy process leads us to the .html part, demonstrating how to create a series of mutually exclusive dropdowns within a table. Despite the complexity, taking it slow will help in grasping the concept effectively. Let's look at a snippet:
Patiently navigate through the instructions highlighted above to implement and understand the complete functionality efficiently.
Check out the final stackblitz here.