I have an array with combination of editable (will be formControl
object) and read-only data(will be a static text on the HTML). Is there a way to do that in Angular? I can use FormArrays
and FormGroups
to add this static text, too but it feels wrong. Let me elaborate on the problem with an example:
Say, I have a JSON object as follows:
itemArray = [{
title: 'fancy item', // not a member of the form (read-only)
quantity: 0 // member of the form (editable)
},
{
title: 'weird item', // not a member of the form (read-only)
quantity: 1 // member of the form (editabe)
}
]
I use FormArrays for the quantity
field of the items.
this.formItems = new FormArray([
new FormGroup(
{
quantity: new FormControl(1, Validators.required),
title: new FormControl('Fancy item') // Readonly text for form group. What's the best way to add a enrichment data for a form group?
}
),
new FormGroup(
{
quantity: new FormControl(1, Validators.required),
title: new FormControl('Weird item') // Readonly text for form group. What's the best way to add a enrichment data for a form group?
}
)
]
);
However, the title is not an editable item. What's the best way to add additional data to a FormGroup
?
Otherwise, I have to create another separate array called items
to manage this additional and non-editable data. So, I can split the fields of item into two separate objects. 1) staticDataForItems
, 2) editableDataForItems
.
this.staticDataForItems = [{
title: 'Weird item',
}
];
this.editableDataForItems = new FormArray([
new FormGroup(
{
quantity: new FormControl(1, Validators.required),
}
),
new FormGroup(
{
quantity: new FormControl(1, Validators.required),
}
)
]
);
This is a solution that I would not prefer. Because, in my use case, I can add items to the array or delete "items" from the array. I don't want to deal with 2 arrays(items and formArray
) which is not future-proof.
If I have a combination of read-only(read-only HTML element) and editable data(input HTML element) data, how can I combine those two arrays into 1 single array.
I want to both benefit from form validation and I would like to add additional data in a good way.
You can find a working example below:
https://stackblitz.com/edit/angular-gw1c6d?file=app%2Fapp.component.ts
Thanks.
formItems[someIndex].value
? – Jota.Toledo