This question is about ngrx-forms
How can I dynamically change the form id in ngrx forms?
I have a list of tabular data. Each of the rows in the table contains details of different products. (each row you can see a different product with different attributes).
EACH ROW IS A NEW PRODUCT
So each of these rows has an edit option. So when clicked it will pop up and populates corresponding form controls that came along with the Product (from the table row). Here the user can edit that particular product details. & save.
When the user closes after saving the form (This form is a side panel) and opens another product the values from the previous product's form persists in the currently opened form.
I feel like this is because the formIds are the same. So to prevent this I think the only way is to assign new formIds dynamically as the user clicks on each edit button.
Is there any way of doing this?
If not possible another way I think is of adding sub forms to the parent form dynamically. But that would cause the parent form tree to grow on each time user clicks edit product.
But if we do like that what if we want to add dynamic controls for some sub property inside those newly created subforms?
...something like nesting FormGroupState(child) inside another FormGroupState(parent) which is then child to parent subform.
I know this is a bit complicated. But is there a way around it?
Author of ngrx-forms here.
I see a couple of options:
1) reset/recreate the form whenever the side-panel is closed/opened. this is the simplest solution, since it allows you to just use a single form state without any ID shenenigans. to do this either add a handler to the form reducer for your closeSidebarAction
(if you have an action like that already) or create a new action. inside the reducer for that action just use formState: createFormGroup('MY_FORM_ID', initialValue)
to fully reset the form state.
2) let ngrx-forms manage all forms by creating one big form array that contains all product forms. this way, each product will have its own form state. I am not a fan of this design, since conceptually there is no such parent form, but instead each product form should be independent.
3) create and manage one form state per product yourself. you can then use the productId
or something similar as part of the form ID. this allows you to persist the form state of a single product even if the user switches to a different product and starts editing it.
In summary, I believe option 1 is what you want. I hope this helps.