数据绑定 – 组件输入属性上的双向数据绑定
我试图在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变量上进行双向数据绑定,如下所示: <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部分的模板语法文档中进行了解释:
另请注意,[(x)]只是属性绑定和事件绑定的语法糖: [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组件使用[(x)]格式将输入属性inputText绑定到ngModel,因此您使用事件绑定(ngModelChange)来通知更改,并在该事件处理程序中通知父组件更改. 在不使用ngModel的其他场景中,重要的是每当属性inputText的值在MyComp组件中发生更改时发出()一个事件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 字
- ofbiz的webservice接口提供(1)-WSDL的生成
- 什么是使用AngularJS与Django的最佳实践
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 字
- Bootstrap Table表格一直加载(load)不了数据的快
- Angular 2,Webpack Uncaught ReferenceError:ve
- bash – 如何使用xargs运行脚本中的用户
- twitter-bootstrap – 简单的Bootstrap页面在iPh
- bootstrap modal 一闪
- vim – 当filetype为none时,如何设置autocmd生效