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

前端 未结 6 727
一生所求
一生所求 2021-01-31 15:42

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:



        
6条回答
  •  眼角桃花
    2021-01-31 16:18

    'If the mountain will not come to Muhammad, then Muhammad must go to the mountain'

    Lets approach this from RxJS side instead of the NgModel side.

    This solution limits us to only use BehaviorSubject's but I think this is a fair trade for having such an easy solution.

    Slap this piece of code into your polyfills.ts. This enables you to bind the .value of a BehaviorSubject to an ngModel

    import { BehaviorSubject } from 'rxjs';
    
    Object.defineProperty(BehaviorSubject.prototype, 'value', {
        set: function(v) {
            return this.next(v);
        }
    });
    

    And just use it like this.

提交回复
热议问题