【问题标题】:Is it possible to perform a two way binding on a custom directive with ngModel?是否可以使用 ngModel 对自定义指令执行双向绑定?
【发布时间】:2017-04-04 10:23:16
【问题描述】:

我的用例完全不同。当我剥离所有其他因素时,它归结为这一点。

假设我有以下输入元素

<input type="text" [customDirective] [(ngModel)]="myValue" >

customDirective 的工作是查看用户输入的值并根据输入动态更改其值。

如何为此实现双向绑定。

我玩过 ControlValueAccessor、DefaultValueAccessor。但是无论我做什么,我都无法实现双向绑定。我一次达到的最大值是模型更新时的视图更新,而不是相反。但是该代码在某处丢失了。

这里是香草plunker link.

PS:我已经提到了以下内容。但是它们都没有帮助实现 w.r.t 到指令的 2 向绑定

http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

angular2 wysiwyg tinymce implementation and 2-way-binding

提前致谢

【问题讨论】:

  • 你可以使用 Pipe 来做同样的事情
  • @ranakrunal9 管道如何改变ngModel 的值?

标签: angularjs angular angularjs-directive angular-ngmodel angular2-ngmodel


【解决方案1】:

终于想通了。

模型到 UI 的更改可以使用 ControlValueAcessor 完成

模型的 UI 可以像下面这样完成

import {Output} from '@angular/core';

使用事件发射器

@Output() ngModelChange = new EventEmitter();

每当数据发生变化时触发事件

this.ngModelChange.emit(YOUR_NEW_VALUE);

这里是详细的例子

Using Tinymce editor as a directive

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-19
    • 2019-07-23
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2020-09-12
    • 2015-03-07
    • 2017-04-29
    相关资源
    最近更新 更多