【发布时间】:2023-03-12 21:57:01
【问题描述】:
使用 Angular 2,在模板驱动的表单中双向绑定很容易——您只需使用香蕉盒语法。您将如何以模型驱动的形式复制这种行为?
例如,这是一个标准的反应形式。让我们假设它比看起来要复杂得多,有大量不同的输入和业务逻辑,因此更适合模型驱动的方法而不是模板驱动的方法。
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 管道中。我怎样才能做到这一点?
【问题讨论】:
标签: angular angular2-forms angular2-formbuilder