在当前版本的 angular2 (alpha 26) 中,我无法让这些样本工作。您现在似乎被迫手动绑定值和更改事件。
这是您表单的完整 TypeScript 示例:
import {Component, View} from 'angular2/angular2';
import {formDirectives, FormBuilder, Control, ControlGroup} from 'angular2/forms';
@Component({
selector: 'todo-app',
injectables: [FormBuilder]
})
@View({
directives: [ formDirectives],
template: `<form [control-group]="todo">
<input #desc [value]="todo.controls.description.value" (keyup)="setControlValue('description', desc.value)">
<input #chk [checked]="todo.controls.checked" type="checkbox" (change)="setControlValue('checked', chk.checked)">
<button (click)="updateTodo($event)">Update</button>
</form>`
})
export class Todo{
todo:ControlGroup;
constructor(builder:FormBuilder){
this.todo = builder.group({
description: new Control('First todo'),
checked: new Control(true)
})
}
updateTodo(event){
event.preventDefault();
console.log(this.todo.controls.description.value);
console.log(this.todo.controls.checked.value);
}
setControlValue(controlName, value){
this.todo.controls[controlName].updateValue(value);
this.todo.controls[controlName].markAsDirty();
}
}
您当然可以通过将输入字段提取到组件中来清理表单标记:
@Component({
selector: 'input-text',
properties: ['control']
})
@View({
template: `<input #ctrl [value]="control.value" (keyup)="setValue(ctrl.value)">`
})
export class InputText{
control: Control;
constructor(){
this.control = new Control('');
}
setValue(value){
this.control.updateValue(value);
this.control.markAsDirty();
}
}
@Component({
selector: 'input-checkbox',
properties: ['control']
})
@View({
template: `<input #ctrl [checked]="control.value" (change)="setValue(ctrl.checked)" type="checkbox">`
})
export class InputCheckbox{
control: Control;
constructor(){
this.control = new Control('');
}
setValue(value){
this.control.updateValue(value);
this.control.markAsDirty();
}
}
然后你必须更新你的 Todo 类的视图部分
@View({
directives: [formDirectives, InputText, InputCheckbox],
template: `<form [control-group]="todo">
<input-text [control]="todo.controls.description"></input-text>
<input-checkbox [control]="todo.controls.checked"></input-checkbox>
<button (click)="updateTodo($event)">Update</button>
</form>`
})