Last active
August 19, 2020 04:35
-
-
Save jwhenry3/3095e6092a4976d3930fa8c92b6c0a36 to your computer and use it in GitHub Desktop.
Component State Manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ChangeDetectorRef} from "@angular/core"; | |
export class StateManager<T> { | |
private _state: T; | |
get state() { | |
return this._state; | |
} | |
set state(value: T) { | |
this._state = value; | |
Object.freeze(this._state); | |
this.changes.markForCheck(); | |
} | |
constructor(private changes: ChangeDetectorRef, private initialState: T) { | |
this.setState(initialState); | |
} | |
setState(newState: T) { | |
this.state = { | |
...newState | |
}; | |
} | |
patchState(partialState: Partial<T>) { | |
this.state = { | |
...this.state, | |
...partialState | |
}; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ChangeDetectionStrategy, ChangeDetectorRef, Component} from "@angular/core"; | |
import {StateManager} from "./00-state-manager"; | |
export interface MyState { | |
key: string | |
} | |
@Component({ | |
selector: 'my-component', | |
template: '<div>{{this.stateManager.state.key}}</div>', | |
changeDetection: ChangeDetectionStrategy.OnPush | |
}) | |
export class MyComponent { | |
stateManager: StateManager<MyState>; | |
constructor(changes: ChangeDetectorRef) { | |
this.stateManager = new StateManager<MyState>(changes, {key: ''}); | |
} | |
ngOnInit() { | |
setTimeout(() => { | |
this.stateManager.setState({ | |
key: 'change!' | |
}) | |
}, 3000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment