angular-redux / form

Keep your Angular2+ form state in Redux
MIT License
41 stars 15 forks source link

connect a form to a store object via a function that calculates the path using state variables #44

Closed kuhlschrank closed 6 years ago

kuhlschrank commented 6 years ago

This is a...

What toolchain are you using for transpilation/bundling?

Environment

NodeJS Version: 6.9.2 Typescript Version: 2.2.2 Angular Version: 4.2 @angular-redux/store version: 3.10.9 @angular/cli version: (if applicable) 1.3.0 OS: win32 x64

Hi,

I'm using angular-redux/form with angular-redux/store and Reactive Forms. It works fine. State is updated when changing inputs in the form. The problem now is, that the connect-Directive does indeed allow passing a function - but this function does not receive the state object (as it does e.g. in the NgRedux.select-function of angular-redux/store).

In my use-case, state looks like this:

{
 currentItemId: 42,
 items: [
  {
   itemId: 41,
   name: "Item41"
  },
  {
   itemId: 42,
   name: "Item42"
  },
  {
   itemId: 43,
   name: "Item43"
  }
 ]
}

So I would like to ´connect´ the currentItem to my input-form

With NgRedux i can

ngRedux.select<ItemState>(state => state.items.filter(i=>i.itemId === state.currentItemId))[0].subscribe(...)

in order to subscribe to changes to the current item.

In angular-redux/forms, I cannot achieve this using a string or an array of strings to select the path for the connect-directive, since I cannot choose the correct item-object with this syntax? I would like to be able to use the same lambda as in the example for NgRedux in my connect-Directive of my form.

Any other solutions?

actra-gschuster commented 6 years ago

Little late to the party, but for anyone getting around here at a later date...

The function you can pass to [connect] is one of your component, so it should be easy to get the state inside that function. Inject ngRedux to the component and use it inside your function for [connect]. E.g.:

constructor(protected ngRedux: NgRedux) {
}

public myConnectPath(): string[] {
    const state: any = this.ngRedux.getState();
    let itemIndex: number = state.items.findIndex((item: any) => item.itemId === state.currentItemId);

    if(itemIndex < 0) {
        // Item not found. handle it, e.g. create it and set itemIndex to the new index
    }

    return ['items', itemIndex];
}
smithad15 commented 6 years ago

@actra-gschuster Good solution. I'm not sure about supplying the state object as part of the library. I will add this to the investigations list for the future. Closing since there seems to be a decent way of accomplishing this.