数据绑定 – Angular2双向数据绑定
我知道Angular2没有双向数据绑定,但有没有办法模仿Angular1.x的双向数据绑定行为?
注意 – 向下滚动ng-model绑定的答案
你实际上可以这样做,只需要调用内部changelistener tick(类似于摘要)来更新区域中的绑定,你可以为它添加一个(keyup)事件。类似地,您也可以使用指令绑定以及组件设置的属性字典。 例:- <input #label (keyup)> <!-- variable #label represented as the element itself and accessible as property on controller instance You can even bind keyup to a function or another another function and pass value from the label property--> 展示为: <p>{{label.value}}</P> 父组件具有文本框和标签。 import { Component,bootstrap} from '@angular/core'; import {Display} from 'display'; @Component({ selector: 'my-app',template: `<p><b>Parent Component:</b><p><input #label (keyup) (change)="handleChange(label.value)"> <p>{{label.value}}</P> <display [text]="label"></display></p></p>`,directives: [Display] }) class MainComponent { label: any; constructor() { } handleChange(label){ this.label = label; console.log(this.label); } } 现在也在子组件中显示它: @Component({ selector: 'edit',template: `<p><b>Child Component:</b></p>{{text.value}}` }) export class Edit { @Input() text:any; } Demo 更新 – 用于双向绑定的ng-model 虽然Angular2默认是一次性绑定,但引入了ngModel糖来实现双向绑定。你可以做到这一点: <input ngControl="name" [(ngModel)]="name"> 这里使用方括号([..])表示事件绑定的属性绑定和圆括号((..))。基本上,当您使用ng-model时,您启用两个绑定ngModel更像是一个事件。在幕后,它创建一个可观察的事件(使用EventEmitter)来跟踪绑定元素中的值更改并分别更新绑定属性。 包括formDirectives: import {FORM_DIRECTIVES} from '@angular/common'; 和形式 <form (ngSubmit)="onSubmit()" let-f="form"> <input ngControl="name" [(ngModel)]="name"> <button>Click me and check console</button> </form> 没有形式 <input [(ngModel)]="name"> <button (click)="onSubmit()">Click me and check console</button> 不再需要了 @Component({ template: .....,directives: [FORM_DIRECTIVES] }) Demo 还可以通过创建ng-model事件及其工作原理来阅读角度为2的双向绑定nice write up from Victor Savkin。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |