Skip to content

Instantly share code, notes, and snippets.

@jwhenry3
Last active August 19, 2020 04:36
Show Gist options
  • Save jwhenry3/4a0815912203b4ddb071d2c18f02b30f to your computer and use it in GitHub Desktop.
Save jwhenry3/4a0815912203b4ddb071d2c18f02b30f to your computer and use it in GitHub Desktop.
Stateful Component
import {ChangeDetectorRef} from "@angular/core";
export class StatefulComponent<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 {StatefulComponent} from "./00-stateful-component";
export interface MyState {
key: string
}
@Component({
selector: 'my-component',
template: '<div>{{this.state.key}}</div>',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent extends StatefulComponent<MyState> {
constructor(changes: ChangeDetectorRef) {
super(changes, {key: ''});
}
ngOnInit() {
setTimeout(() => {
this.setState({
key: 'change!'
})
}, 3000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment