Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep state in angular 2?

Tags:

angular

I just getting my head around angular 2 and looking at designing a wizard type of application. Components on page 1 need to communicate data to components on other pages. Thinking of using a service to keep state/data which is injected in the next view/component of the wizard. The whole thing should be loosely coupled. I dont think it is useful to design a observable pattern because a component that is on one of the next pages/views are not visible yet. What new features in angular 2 could be used to solve this?

like image 459
bier hier Avatar asked Apr 29 '16 07:04

bier hier


2 Answers

I suggest keeping your state centralized using for example Redux. You would then use the @Input() and @Output() of angular to propagate your state to components, and dispatch state changes from your components.

You would have a top level component that subscribes to state changes, and propagate those using child component @Inputs. Your child components would emit requests of state changes using @Outputs() to the top level component, which in turn updates the central state.

This way your individual component does not have to know anything about how state is stored and updated, they simply provide functionality and accepts input parameters that can have desired effect on their functionality.

If you have many deeply nested components they themselves also use @Input() and @Output() to provide the functionality, and does not communicate with any state store directly.

I'm myself using this method and it keeps each component very lean and reusable, while making it super easy to keep track of your state, and reduces the complexity of synchronizing your state across components a lot.

You should in addition have a look at ChangeDetectionStrategy and ChangeDetectorRef since you can simplify the component change detection using this method. All of your child components can generally use what's called the OnPush checking strategy, which means their change detection will only be run as their @Input() properties have changed. Since this is the only way state will change in this case you can tell angular not the check for changes otherwise. This will also help out with performance.

Note that you could keep the state using just a regular angular2 service, but something like Redux gives you some things for free like for example the dev tools provided. If you go with Redux, also have a look at Immutable.js as it is important not to mutate the state directly using Redux.

like image 160
jgranstrom Avatar answered Nov 14 '22 03:11

jgranstrom


Check @ngrx/store

RxJS powered state management inspired by Redux for Angular2 apps

like image 30
dstr Avatar answered Nov 14 '22 05:11

dstr