Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 883
mhelvens Avatar asked Jul 29 '16 15:07

mhelvens


People also ask

What does [( ngModel )] mean?

ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form. We can use ngModel with: input. text.

Is ngModel two way binding?

ngModel Directive The [(ngModel)] syntax is the recommended way of two-way data binding. The ngModel directive with [] syntax is used for one-way data binding. [ngModel] binds a value to a property to UI control.

Which import to be used if the components have [( ngModel )] for two way binding expression?

We use Property binding & Event binding to achieve the two-way binding.


1 Answers

This is a simple solution, as you said in your question. I think there's nothing simpler than what you already provided.

<input type="text"         [ngModel]="subject | async"        (ngModelChange)="subject.next($event)" /> 
like image 76
activedecay Avatar answered Sep 16 '22 15:09

activedecay