本文介绍了如何将我自己的RxJS主体双向绑定到[(ngModel)]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有通过RxJS传递的简短方法 Subject BehaviorSubject 到Angular 2双向绑定的指令?很长的路要走如下:

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" />
    `
})

我相信async管道只是单向的,所以这还不够. Angular 2是否提供了一种简短的方法来做到这一点? Angular 2也使用RxJS,所以我希望会有一些内在的兼容性.

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.

也许我可以创建一个新的类似ngModel的指令来实现这一点吗?

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

推荐答案

让我们从RxJS方面而不是NgModel方面解决这个问题.

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

此解决方案将我们限制为仅使用BehaviorSubject,但是我认为这是一个公平的交易,因为拥有如此简单的解决方案.

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

将这段代码拍入您的polyfills.ts中.这使您可以将BehaviorSubject.value绑定到ngModel

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);
    }
});

然后像这样使用它.

<ng5-slider [(value)]="fooBehaviorSubject.value" ...

这篇关于如何将我自己的RxJS主体双向绑定到[(ngModel)]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 02:37