Skip to content

Instantly share code, notes, and snippets.

@jwhenry3
Last active August 19, 2020 04:35
Show Gist options
  • Save jwhenry3/3095e6092a4976d3930fa8c92b6c0a36 to your computer and use it in GitHub Desktop.
Save jwhenry3/3095e6092a4976d3930fa8c92b6c0a36 to your computer and use it in GitHub Desktop.
Component State Manager
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
};
}
}
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