我正试图在 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 anngModel
input property and anngModelChange
output property. That’s a specific example of a more general pattern in which it matches[(x)]
to anx
input property for Property Binding and anxChange
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/