Search code examples
angularrxjsobservable

Extending Angular 2 ngModel directive to use observables


Angular 2 ngModel directive works with variables and functions like

<input [ngModel]="myVar" (ngModelChange)="myFunc($event)" />

Instead of variables and functions, I would like to use BehaviorSubjects instead

<input [ngModel]="mySubject | async" (ngModelChange)="mySubject.next($event)" />

Is there a safe way to extend ngModel or use some kind of macro to reduce repetition in my templates?

<input [myNewNgModel]="mySubject" />

Solution

  • I don't know why you wouldn't just use reactive forms, but this was a fun puzzle. I created a directive that will alter the model value to the BehaviorSubject's value. And any changes will call .next on the BehaviorSubject for you.

    Usage will look like this

    <input type="text" [ngModel]="ngModelValue" appRxModel> 
    

    Here is the stackblitz, enjoy