使用Angular 2,双向绑定在模板驱动的表单中很容易——只需使用香蕉盒语法即可.您将如何以模型驱动的形式复制这种行为?
例如,这是一个标准的react 形式.让我们假设它比看起来复杂得多,有很多很多不同的输入和业务逻辑,因此更适合于模型驱动的方法,而不是模板驱动的方法.
export class ExampleModel {
public name: string;
// ... lots of other inputs
}
@Component({
template: `
<form [formGroup]="form">
<input type="text" formControlName="name">
... lots of other inputs
</form>
<h4>Example values: {{example | json}}</h4>
`
})
export class ExampleComponent {
public form: FormGroup;
public example: ExampleModel = new ExampleModel();
constructor(private _fb: FormBuilder) {
this.form = this._fb.group({
name: [ this.example.name, Validators.required ]
// lots of other inputs
});
}
this.form.valueChanges.subscribe({
form => {
console.info('form values', form);
}
});
}
在subscribe()
中,我可以对表单值应用各种逻辑,并根据需要映射它们.但是,我不想映射表单中的每个输入值.我只想看到整个employee
模型更新时的值,方法类似于[(ngModel)]="example.name"
,并显示在模板的json管道中.我怎样才能做到这一点?