注意 - 向下滚动 ng-model 绑定的答案
您实际上可以这样做,只是您需要调用内部 changelistener tick(类似于摘要)来更新区域中的绑定,您只需为此添加一个 (keyup) 事件。同样,您也可以使用指令绑定以及 properties 组件设置字典。
例子:-
<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
更新 - 用于 2 向绑定的 ng-model
虽然Angular2默认是一次性绑定的,但引入ngModelsugar实现2路绑定。例如,您可以这样做:
<input ngControl="name" [(ngModel)]="name">
这里使用方括号 ([..]) 建议属性绑定和圆括号 ((..)) 用于事件绑定。基本上,当您使用ng-model 时,您启用了两个绑定ngModel 更像是一个事件。在幕后,它创建了一个可观察事件(使用EventEmitter)来跟踪绑定元素中的value 更改并分别更新绑定属性。
例如:-
包括 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>
不再需要了
在视图注释中包含 formDirectives 依赖。
@Component({
template: .....,
directives: [FORM_DIRECTIVES]
})
Demo
还可以通过创建 ng-model 事件及其工作原理阅读有关 angular2 中双向绑定的 nice write up from Victor Savkin。