双向的角2 NgModel结合和变异绑定属性? [英] Two-way binding in Angular 2 with NgModel and mutating bound property?

查看:977
本文介绍了双向的角2 NgModel结合和变异绑定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的角2测试版5。

I am using Angular 2 beta 5.

下面是我的看法:

<textarea [(ngModel)]="pendingMessage" (keydown.enter)="sendMessage()"></textarea>

这是我的组件:

@Component({
    //...
})
export class AppComponent {
    private _pendingMessage: string;

    public get pendingMessage() {
        return this._pendingMessage;
    }

    public set pendingMessage(value: string) {
        this._pendingMessage = value;
    }

    constructor() {
        this.pendingMessage = "initial stuff"; //this shows up in the text field initially
    }

    public sendMessage() {
        console.log(this.pendingMessage); //here, pending message is indeed whatever I typed in the text field
        this.pendingMessage = "blah";
        //here I expected the textfield to now contain "blah", but it doesn't
    }
}

这种双向绑定的整个概念似乎是正常的工作。当我在字段中键入一些文字,并敲回车,我可以看到 pendingMessage 确实不管我输入到该领域。

The whole concept of this two-way binding seems to be working alright. When I type some text in the field and hit enter, I can see that pendingMessage is indeed whatever I typed into the field.

不过,在下面,我尝试设置 pendingMessage 嗒嗒,我也行期待这个更新文本框含有嗒嗒。这是为什么不是这样?这难道不是双向绑定的地步?

However, in the line below where I try to set the pendingMessage to "blah", I was also expecting this to update the textfield to contain "blah". Why is this not the case? Isn't that the point of two-way bindings?

我知道,角2不能神奇地知道什么时候值的变化,但我希望它评估事件之后会做一个肮脏的检查。有没有什么办法让它自动做这样的事情,或在某种程度上拿起变化?我想避免使用适用

I know that Angular 2 can't magically know when values change, but I was hoping it would do a dirty check after evaluating the event. Is there any way to make it do such a thing automatically or somehow pick up the change? I would like to avoid using apply.

推荐答案

更新

添加 ngDefaultControl

<paper-input ngDefaultControl [(ng-model)]="address">

另请参阅 https://github.com/angular/angular/issues/5360

**

我想这是 ngModel 实施的电流限制。它结合的元素的字段,但为的textarea 它的文本应该绑定到AFAIR领域。看来的textarea 触发一个事件的 ngModel 听这使得它在一个方向努力。

I guess this is a current limitation of the ngModel implementation. It binds to the value field of the element but for textarea it's the text AFAIR field it should bind to. It seems the textarea fires an event that ngModel listens to which makes it work in one direction.

您可以解决此通过实现自定义 ValueAccessor ​​

You can work around this by implementing a custom ValueAccessor

另请参阅结果
- ngModel定制Values​​Accessor ​​结果
- 角2自定义表单输入结果
- <一个href=\"http://stackoverflow.com/questions/33981270/bind-angular-2-model-to-polymer-dropdown/33986250\">Bind角2型聚合物下拉

See also
- ngModel custom ValuesAccessor
- Angular 2 custom form input
- Bind angular 2 model to polymer dropdown

这篇关于双向的角2 NgModel结合和变异绑定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆