The Angular Model - ngx-model
by @tomastrajan
Simple state management with minimalistic API, one way data flow, multiple model support and immutable data exposed as RxJS Observable.
Documentation
- StackBlitz Demo
- Demo & Documentation
- Blog Post
- Changelog
- Schematics - generate
ngx-model
services using Angular CLI schematics!
Getting started
-
Install
ngx-model
npm install --save ngx-model
or
yarn add ngx-model
-
Import and use
NgxModelModule
in youAppModule
(orCoreModule
); -
Import and use
Model
andModelFactory
in your own services.;;; -
Use service in your component. Import and inject service into components constructor. Subscribe to services data in template
todosService.todos$ | async
or explicitlythis.todosService.todos$.subscribe(todos => { /* ... */ })
;;;
Available Model Factories
Models are created using model factory as shown in above example this.model = this.modelFactory.create([]);
.
Multiple model factories are provided out of the box to support different use cases:
create(initialData: T): Model<T>
- create basic model which is immutable by default (JSON
cloning)createMutable(initialData: T): Model<T>
- create model with no immutability guarantees (you have to make sure that model consumers don't mutate and corrupt model state) but much more performance because whole cloning step is skippedcreateMutableWithSharedSubscription(initialData: T): Model<T>
- gain even more performance by skipping both immutability and sharing subscription between all consumers (eg situation in which many components are subscribed to single model)createWithCustomClone(initialData: T, clone: (data: T) => T)
- create immutable model by passing your custom clone function (JSON
cloning doesn't support properties containing function or regex so custom cloning functionality might be needed)
Relationship to Angular Model Pattern
This is a library version of Angular Model Pattern.
All the original examples and documentation are still valid. The only difference is that
you can install ngx-model
from npm instead of having to copy model pattern
implementation to your project manually.
Check out the Blog Post and Advanced Usage Patterns for more how-tos and examples.
Getting started with Schematics
- make sure you're using this in project generated with Angular CLI.
- install dependency with
npm i -D @angular-extensions/schematics
- generate model services with
ng g @angular-extensions/schematics:model --name path/my-model
- or with
ng g @angular-extensions/schematics:model --name path/my-model-collection --items
form model of collection of items - add your own model service methods and tests