Comments (6)
from ngrx-forms.
Not being able to use complex objects as values of form controls is an unfortunate side-effect of a design decision that I made very early on when starting to work on this library. However, I decided to stick with it and since then it has become an integral part of the design. I have thought about how I could add support for complex object values but it would be very hard and might even be impossible (especially due to the way the form states are typed). Therefore, currently I have no plans to add support for this.
However, here are some suggestions that might help you:
In my applications I have found that storing only IDs and then accessing the business objects separately helps with keeping each aspect focused on what it does best (managing forms vs your custom business logic). Usually the place where I need to bring both of them together is inside of an effect or service in which case I simply combine both the selected ID and the business object from the store with a withLatestFrom
. You can of course even write a custom selector that does all of this for you in a re-usable way.
An alternative would be (although this somewhat breaks the separation between forms and domain logic) to store the list of allowed values for the autocomplete as a user-defined property inside the form control. This way you can always look up the proper value from the form state alone when you need it.
Or you could write a directive that reacts to value changes on the autocomplete and sets the selected user as a user-defined property on the control.
And yet another option would be to react to value changes inside the parent reducer in which the form state reducer is embedded and then select the correct user based on the ID to run your business logic against (assuming that the users are stored as part of the parent state of the form state).
I agree that all of these options require some overhead compared to simply storing the complex object as a form value. However, as you can see there are a couple of ways to do it that aren't too bad and can be made re-usable. So you can choose which one fits you best and go with that.
PS: I am not sure what you mean by "especially when a route is opened directly by url". How would storing the whole user in the form state help you here?
from ngrx-forms.
Thanks for your quick response.
I agree that keeping form state and business objects separate has some major advantages in the overall design. However, this would make our migration to ngrx-forms quite expensive. For now I wanna give the user definied properties approach a try:
type PrimitiveValueProjector<T> = (complex: T) => null | undefined | string | number | boolean;
function createComplexValueReducerInterceptor<T, V>(
formId: string,
controlName: keyof T,
projector: PrimitiveValueProjector<V>) {
return (defaultReducer: ActionReducer<FormGroupState<T>>) => {
return (state: FormGroupState<T>, action: Action) => {
if (action.type === SetValueAction.TYPE) {
const setValueAction = action as SetValueAction<V>;
const value = setValueAction.payload.value;
const valueType = typeof value;
const isNonPrimitiveValue = value !== null && ['string', 'number', 'boolean', 'undefined'].indexOf(valueType) === -1;
if (setValueAction.controlId === `${formId}.${controlName}` && isNonPrimitiveValue) {
const updateValue: {[k in keyof T]?: any} = {};
updateValue[controlName] = setValue(projector(value));
const updateUserDefinedProperty: {[k in keyof T]?: any} = {};
updateUserDefinedProperty[controlName] = setUserDefinedProperty('complexValue', value);
return updateGroup<T>(updateValue, updateUserDefinedProperty)(state);
}
}
return defaultReducer(state, action);
};
}
}
...
const useId = value => value.id;
const reducer = compose(
createComplexValueReducerInterceptor<Inspection, User>('detail-form', 'author', useId),
createComplexValueReducerInterceptor<Inspection, User>('detail-form', 'approver', useId)
)(defaultReducer);
from ngrx-forms.
Alright, I had a look at your code. I see one issue in that it only works for one level of nesting. If you want to support further nested elements you'll need to use a slightly different approach, e.g. this:
type PrimitiveValueProjector<T> = (complex: T) => null | undefined | string | number | boolean;
const ORIGINAL_VALUE_PROPERTY_NAME = 'originalValue';
function createComplexValueReducerInterceptor<T, V>(
controlId: string,
projector: PrimitiveValueProjector<V>,
) {
return (defaultReducer: ActionReducer<FormGroupState<T>>) => {
return (state: FormGroupState<T>, action: Action) => {
if (action.type === SetValueAction.TYPE) {
const setValueAction = action as SetValueAction<V>;
const value = setValueAction.payload.value;
const valueType = typeof value;
const isNonPrimitiveValue = value !== null && ['string', 'number', 'boolean', 'undefined'].indexOf(valueType) === -1;
if (setValueAction.controlId === controlId && isNonPrimitiveValue) {
const updateControl = (state: AbstractControlState<any>) => {
if (state.id !== controlId) {
return state;
}
state = setValue(projector(value), state);
state = setUserDefinedProperty(ORIGINAL_VALUE_PROPERTY_NAME, value, state);
return state;
};
return updateRecursive(state, updateControl);
}
}
return defaultReducer(state, action);
};
}
}
from ngrx-forms.
Thanks for your code improvments. I tried the value-converter approach and I think it is the best for my use case.
from ngrx-forms.
Closing this. If you have any other questions feel free to open another issue or comment here again and I'll re-open it.
from ngrx-forms.
Related Issues (20)
- Sure, just replace the players update with something like this:
- `NgrxFormControlDirective`: Update view when `ngrxValueConverter` changes HOT 1
- Pattern: Supply different "feature state" into the form reducer? HOT 1
- mat-radio checked not working? HOT 1
- Type inference is incorrect with readonly[]
- Question: Bind server-side validation to ngrx-forms forms
- [QUESTION] - Validation of a nested formState HOT 1
- Primitive unions are not supported
- Add compatibility with typescript 4.8 HOT 1
- New Angular Version 15 with breaking changes on Material to mat-list-options HOT 3
- No valid view adapter for Slider with Angular Material 15
- FormArrayState, the state doesn't update when SetValueActions are disptached
- Add compatibility with Typescript 5
- material 15+ (MCD based components) compatibility HOT 1
- Angular 16 support HOT 4
- Enable/Disable nested array properties HOT 3
- Programmatically Triggering Async Validation HOT 3
- Add sortArray function HOT 4
- Control validation order, run async after synchronous complete without error
- Question: Update parent form state based on child control states
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from ngrx-forms.