How to two-way bind my own RxJS Subject to an [(ngModel)]?

mhelvens picture mhelvens · Jul 29, 2016 · Viewed 9.7k times · Source

Is there a short and simple way to pass an RxJS Subject or BehaviorSubject to an an Angular 2 directive for two-way binding? The long way to do it would be as follows:

@Component({
    template: `
        <input type="text" [ngModel]="subject | async" (ngModelChange)="subject.next($event)" />
    `
})

I'd like to be able to do something like this:

@Component({
    template: `
        <input type="text" [(ngModel)]="subject" />
    `
})

I believe the async pipe is only one-way, so that's not enough. Does Angular 2 provide a short and simple way to do this? Angular 2 uses RxJS too, so I expected there to be some inherent compatibility.

Could I perhaps create a new ngModel-like directive to make this possible?

Answer

activedecay picture activedecay · Apr 16, 2020

This is a simple solution, as you said in your question. (Nothing simpler than what you already provided)

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