Angular track is your app in mobile, tablet or desktop view?
A new app is designed to be available on mobile, tablet and desktop, like it should be. But we discovered that views are totally different on some pages, if we do it on the css way with media-queries, display: none depending on the window size, we will have a lot of html generated that we will hide. To avoid this we can do it also with *ngIf, so it is only rendered when needed. But we don’t wan’t to listen constant on the window object. Only one time should be enough for the whole application, so we place it on the store.
1. Create the state, action and reducer
We need 3 states for our application: mobile, when the window is in mobile size, tablet for tablet size and desktop.
Only one action is needed, when the screen size changes it need to be called. Mobile max width and tablet max width can be adjusted as need.
The reducer for screen state is very easy, initial we set everything on false, once the SET_SCREEN action is send, we take the right settings.
Don’t forget to register your screenReducer in the rootReducer.
2. Create an appSandbox
With an architecture where separations of concerns are important. We decide to make sandboxes. Our component doesn’t need to know that we store everything in the store. If we want to adjust these principles, of no longer use a store our use another one, only the sandboxes needs to be adjusted.
3. Create the window listener
Observable.fromEvent(window, ‘resize')
can be used to subscribe on the window, resize function.
To avoid a lot of changes on one time, we add a debounceTime of 200 ms. We are listen to an event if it changes, only the moment the resize event is called interest us. After we get the notification the event was executed we want to know the innerWidth on the window. To map this we can use the mapTo operator. To avoid duplicates on our stream, we add a distinctUntilChanged. Resize is only called from the moment the window is resized, so we add a value to startWith.
There is no need to inject window in the app constructor. Window is a reserved word in javascript, it is always available. So why should you choose to inject it. Not everything we write in our angular application is angular. Sometimes we need to keep with the base functionality of our framework!