Last active
August 19, 2020 04:36
-
-
Save jwhenry3/4a0815912203b4ddb071d2c18f02b30f to your computer and use it in GitHub Desktop.
Stateful Component
This file contains hidden or 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 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 | |
| }; | |
| } | |
| } | |
This file contains hidden or 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 {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