data-binding - 组件输入属性上的双向数据绑定(bind)

标签 data-binding angular bidirectional

我正试图在 angular2 上做一些事情,但我无法找到有关此行为的信息。

我有一个应用程序实现了这样一个自定义组件:

import {Component,Input} from 'angular2/core'
    @Component({
      selector:'my-comp',
      template:`<input type="text" style="text-align:center; [(ngModel)]="inputText"> <p>{{inputText}}</p>`
    })

    export class MyComp{
      @Input() inputText : string;
    }

我正在尝试对组件中的 inputText 变量进行双向数据绑定(bind),如下所示:

<my-comp [(inputText)]="testString"></my-comp>

testString 是在 MyApp.ts 中定义的变量,其中包含一个字符串。我希望在用户修改我的 inputText 时修改我的 testString 变量。

这是一个带有简单示例代码的 Plunker:https://plnkr.co/edit/zQiCQ3hxSSjCmhWJMJph?p=preview

有没有办法让这个工作变得简单?我是否必须在自定义组件和重载函数上实现 Angular2 类才能使其像 ngModel 一样工作?我是否必须创建一个 EventEmitter 类型的 inputTextChanged 变量,当它发生变化时发出我的数据并做这样的事情:

<my-comp [inputText]="testString" (inputTextChanged)="testString = $event;"></my-comp>

提前谢谢你。

最佳答案

这在模板语法文档中有解释,在 Two-Way Binding with NgModel 中部分:

<input [(ngModel)]="currentHero.firstName">

Internally, Angular maps the term, ngModel, to an ngModel input property and an ngModelChange output property. That’s a specific example of a more general pattern in which it matches [(x)] to an x input property for Property Binding and an xChange output property for Event Binding.

We can write our own two-way binding directive/component that follows this pattern if we're ever in the mood to do so.

另请注意 [(x)]只是属性绑定(bind)和事件绑定(bind)的语法糖:

[x]="someParentProperty" (xChange)="someParentProperty=$event"

在你的情况下,你想要

<my-comp [(inputText)]="testString"></my-comp>

所以你的组件必须有一个 inputText输入属性和 inputTextChange输出属性(这是一个 EventEmitter )。

export class MyComp {
  @Input()  inputText: string;
  @Output() inputTextChange: EventEmitter<string> = new EventEmitter();
}

每当您的组件更改 inputText 的值时,将更改通知父级,发出一个事件:

inputTextChange.emit(newValue);

在您的场景中,MyComp 组件绑定(bind)输入属性 inputText使用 [(x)]格式化为 ngModel,所以你使用了事件绑定(bind) (ngModelChange)收到更改通知,并在该事件处理程序中将更改通知给父组件。

在其他不使用 ngModel 的情况下,重要的是 emit()每当属性值 inputText 时发生事件MyComp 组件中的更改。

关于data-binding - 组件输入属性上的双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608814/

相关文章:

c - FTDI MPSSE 从双向 DATA 引脚读取

julia - Julia 中的双向字典

c# - 将相对源根父控件的属性绑定(bind)到子类的附加属性 - 使应用程序崩溃

angular - 查询根据结果集的大小而不是数据集的大小进行缩放

c++ - ICU 布局示例以不同于 Microsoft 记事本和 Word 的方式呈现文本

html - 运行 ng build 时,index.html 什么都不做?

angular2-multiselect-dropdown 不禁用选择所有过滤结果

c# - UWP x :bind two-way binding

嵌套控件中的 silverlight 绑定(bind)组合框

javascript - Angujar JS 表单问题中未定义范围