• Stars
    star
    133
  • Rank 272,600 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Angular Model. Simple state management with minimalistic API, one way data flow, multiple model support and immutable data exposed as RxJS Observable.

⚠️ IMPORTANT

THIS REPO / PACKAGE HAS BEEN DEPRECATED

Please use new @angular-extensions/modelpackage / repo which is a combination of both the model library and related schematics which renders this package uselsess. On the other hand, feel free to keep using ngx-model if it suits your needs, it will not be deleted, but there will be no further development. Please, have a look into migration section in the new documentation.

The Angular Model - ngx-model

by @tomastrajan

npm npm npm Build Status Twitter Follow

Simple state management with minimalistic API, one way data flow, multiple model support and immutable data exposed as RxJS Observable.

Documentation

ngx-model dataflow diagram

Getting started

  1. Install ngx-model

    npm install --save ngx-model
    

    or

    yarn add ngx-model
    
  2. Import and use NgxModelModule in you AppModule (or CoreModule)

    import { NgxModelModule } from 'ngx-model';
        
    @NgModule({
      imports: [
        NgxModelModule
      ]
    })
    export class CoreModule {}
  3. Import and use Model and ModelFactory in your own services.

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    import { ModelFactory, Model } from 'ngx-model';
        
    @Injectable()
    export class TodosService {
            
      private model: Model<Todo[]>;
      
      todos$: Observable<Todo[]>;
            
      constructor(private modelFactory: ModelFactory<Todo[]>) {
        this.model = this.modelFactory.create([]); // create model and pass initial data
        this.todos$ = this.model.data$; // expose model data as named public property
      }
        
      toggleTodo(id: string) {
        // retrieve raw model data
        const todos = this.model.get();
            
        // mutate model data
        todos.forEach(t => {
          if (t.id === id) {
            t.done = !t.done;
          }
        });
            
        // set new model data (after mutation)
        this.model.set(todos);
      }
        
    }
  4. Use service in your component. Import and inject service into components constructor. Subscribe to services data in template todosService.todos$ | async or explicitly this.todosService.todos$.subscribe(todos => { /* ... */ })

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subject } from 'rxjs';
    
    import { TodosService, Todo } from './todos.service';
    
    @Component({
      selector: 'ngx-model-todos',
      templateUrl: `
        /* ... */
        <h1>Todos ({{count}})</h1>
        <ul>
          <!-- template subscription to todos using async pipe -->
          <li *ngFor="let todo of todosService.todos$ | async" (click)="onTodoClick(todo)">
            {{todo.name}}
          </li>
        </ul>
      `,
    })
    export class TodosComponent implements OnInit, OnDestroy {
    
      private unsubscribe$: Subject<void> = new Subject<void>();
      
      count: number;
     
      constructor(public todosService: TodosService) {}
    
      ngOnInit() {
        // explicit subscription to todos to get count
        this.todosService.todos
          .pipe(
            takeUntil(this.unsubscribe$) // declarative unsubscription
          )
          .subscribe(todos => this.count = todos.length);
      }
      
      ngOnDestroy(): void {
        // for declarative unsubscription
        this.unsubscribe$.next();
        this.unsubscribe$.complete();
      }
    
      onTodoClick(todo: Todo) {
        this.todosService.toggleTodo(todo.id);
      }
    
    }

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 skipped
  • createMutableWithSharedSubscription(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

  1. make sure you're using this in project generated with Angular CLI.
  2. install dependency with npm i -D @angular-extensions/schematics
  3. generate model services with ng g @angular-extensions/schematics:model --name path/my-model
  4. or with ng g @angular-extensions/schematics:model --name path/my-model-collection --items form model of collection of items
  5. add your own model service methods and tests

Generating model using schematics

More Repositories

1

angular-ngrx-material-starter

Angular, NgRx, Angular CLI & Angular Material Starter Project
TypeScript
2,832
star
2

angular-js-es6-testing-example

Enhanced testing of Angular JS 1.X applications using ES6 modules
JavaScript
171
star
3

react-typescript-webpack

Seed for building React app using Typescript and Webpack build using FLUXless architecture
TypeScript
116
star
4

component-pattern-for-angular-js-1-x

Example of implementation of Component pattern for Angular JS 1.X using ES6 & Webpack
JavaScript
70
star
5

angular-architecture-example

TypeScript
68
star
6

medium-enhanced-stats

Google Chrome Extension for enhanced Medium stats! Get insight into total view count with new table summary row...
JavaScript
67
star
7

angular-library-architecture-example

Angular Library Architecture Example
TypeScript
40
star
8

angular-model-pattern-example

Model pattern for Angular (2, 4, ...), manage and share your state with simple services using RxJS Subjects and Observables
HTML
36
star
9

ngx-model-hacker-news-example

Example repository with Hacker News implementation using Angular, Angular Material & ngx-model
TypeScript
27
star
10

releasebot

TypeScript
18
star
11

angular-lazy-lib-demo

How to lazy load modules from Angular libraries example
TypeScript
17
star
12

workshop-angular-schematics

TypeScript
13
star
13

grunt-ngsrc

Find and add your Angular.js source files into index.html automatically
JavaScript
11
star
14

angular-monorepo-enterprise-starter

Angular Monorepo Enterprise Starter
TypeScript
10
star
15

jasmine-async-sugar

Simple drop-in syntax sugar for Jasmine 2.X test framework to enhance testing of async (promise) functionality to be used with Angular 1.X
JavaScript
8
star
16

meetup-angular-material-themes-example

Angular Material Themes Code Example for Angular Meetup Zurich 21. 8. 2017
TypeScript
8
star
17

node-babel-es6-example

Use ES6 module syntax in node.js with minimalized Babel influence (because node.js already supports most ES6 features)
JavaScript
5
star
18

tomastrajan-com

TypeScript
4
star
19

ngrx-test

WIP
TypeScript
2
star
20

webpack-seed

Fully featured webpack build
JavaScript
2
star
21

angular-bootstrap-example

Minimalistic Angular 6 Bootstrap 4 integration example
TypeScript
2
star
22

ngconsultant

ng-consultant website
TypeScript
2
star
23

Quado

Android arkanoid (breakout) type game
Java
2
star
24

angular-rxjs-websocket-example

TypeScript
2
star
25

complete-angular2-seed

Feature complete seed for Angular 2.0 applications with Typescript, Webpack build and focus on code style, testing and production ready packaging
TypeScript
1
star
26

fintech-example

TypeScript
1
star
27

ngx-model-example

Simple example project of using ngx-model in Angular application
TypeScript
1
star
28

grunt-npm-install-all

Run npm install in all matching directories with package.json file (exclude package.json files in already installed node_modules directories)
JavaScript
1
star
29

ultimate-es6-migration-guide-modules

Ultimate ES6 / ES2015 migration guide - Modules - forward backward compatibility & caveats
JavaScript
1
star
30

avatarjs-hapijs-seed

Seed project for Avatar.js (running node.js in JVM) & hapi.js (node.js web app framework)
Batchfile
1
star
31

http-request-cancelation-example

TypeScript
1
star
32

Quado-server

Score sharing backend
JavaScript
1
star
33

angular2-typescript-webpack

Angular 2 Typescript Webpack starter project
TypeScript
1
star
34

angular-signals-effect

Created with StackBlitz ⚑️
TypeScript
1
star
35

angular-elements-cd-example

TypeScript
1
star