ngxs-history-plugin
v1.0.2
Published
A plugin that captures the state changes of an angular application which uses ngxs state management library
Downloads
6
Maintainers
Readme
ngxs-history-plugin
This plugin is designed to work with the NGXS state management library.
With this plugin we are able to capture the state changes and revert (undo) to the previous state by dispatching an action
Demo
🚀 See it in action on Stackblitz
How to use
- Install from NPM
- Import the module in the
app.module
- Use the
undoable
decorator - Dispatch the
undo
action
1. Install from NPM
registry
If you use npm
npm i ngxs-history-plugin
If you use yarn
yarn add ngxs-history-plugin
2. Import the module in the app.module
Import the package module
import { NgxsHistoryModule } from 'ngxs-history-plugin'
Import the Angular module
@NgModule({
declarations: [AppComponent],
imports: [
NgxsModule.forRoot([], {
developmentMode: !environment.production,
}),
NgxsHistoryModule.forRoot(), // <-- import the module
],
bootstrap: [AppComponent],
})
export class AppModule {}
You can optionally use the following PluginOptions
| Name | Type | Required | Description | | ------------- | ------ | -------- | ------------------------------------------------------------------------- | | historyLength | number | no | the number of elements to keep in the history. Empty means no restriction |
Example
@NgModule({
declarations: [AppComponent],
imports: [
NgxsModule.forRoot([], {
developmentMode: !environment.production,
}),
NgxsHistoryModule.forRoot({
historyLength: 25, // <-- use the historyLength option
}),
],
bootstrap: [AppComponent],
})
export class AppModule {}
3. Use the undoable
decorator
Set the undoable
decorator in the state file for the actions you want to handle.
Example:
@Action(AddTodo)
@Undoable(AddTodo) // <-- set the decorator and provide the action to handle
addTodo(ctx: StateContext<TodoStateModel>, action: AddTodo) {
const state = ctx.getState()
const newItem = {
title: action.title,
}
ctx.setState({
...state,
items: [...state.items, newItem],
})
}
4. Dispatch the undo
action
Import the Undo Action
import { NgxsHistoryUndo } from 'ngxs-history-plugin'
Dispatch the action
undo() {
this.store.dispatch(new NgxsHistoryUndo());
}
Enjoy :)