如何使用反应式表单将表单绑定到 Angular 6 中的模型? [英] How can I bind a form to a model in Angular 6 using reactive forms?

查看:24
本文介绍了如何使用反应式表单将表单绑定到 Angular 6 中的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 angular 6 之前,我使用 [(ngModel)] 将我的表单字段直接绑定到模型.现在已弃用(不能与反应式表单一起使用),我不确定如何使用表单值更新我的模型.我可以使用 form.getRawValue() 但这需要我用新的 rawValue 替换我当前的模型 - 这不是有利的,因为我的主模型比本地表单模型更大并且有更多的字段.

Prior to angular 6, I was using [(ngModel)] to directly bind my form field to the model. This is now deprecated (can't use with reactive forms) and I am not sure how to update my model with the form values. I could use form.getRawValue() but this would require me to replace my current model with the new rawValue - this is not favourable since my main model is larger and has more fields than the local form model.

有什么想法吗?

推荐答案

不要使用 [(ngModel)]!反应式形式要好得多.他们使手动 ngModel 绑定过时了,并且他们有一些非常漂亮的内置功能,我将在本答案中介绍其中的几个.

Don't use [(ngModel)]! Reactive forms are much nicer. They make manual ngModel bindings obsolete, and they have some pretty sweet built-in features only a couple of which I'm going to cover in this answer.

如果要绑定到表单控件(例如文本输入),请使用以下模板语法:

If you're binding to a form control such as a text input, use this template syntax:

<ng-container [formGroup]="this.myFormGroup">
    <input type="text" formControlName="field1">
    <input type="text" formControlName="field2">
    <ng-container formGroupName="subgroupName">
        <input type="text" formControlName="subfield2">
    </ng-container>
    <input type="text" formControlName="myRequiredField">
</ng-container>

(field1field2subgroupNamesubfield2myRequiredField 都是与表单部分相对应的任意控件和控件组名称,请在创建 FormGroup 对象时参见下文.)

(field1, field2, subgroupName, subfield2, and myRequiredField are all arbitrary control and control group names that correspond to parts of your form, see below when creating the FormGroup object.)

FormGroup 模型的只读数据绑定在您的模板中的访问方式略有不同:

Read-only data bindings to the model of the FormGroup are accessed a little differently in your template:

{{ this.myFormGroup.get('field1').value }}
{{ this.myFormGroup.get('subgroupName.subfield2').value }}
<!-- Hint: use an array if you have field names that contain "." -->
{{ this.myFormGroup.get(['subgroupName', 'subfield2']).value }}

创建FormGroup

在您的组件类中,在 constructor()(这应该在模板呈现之前)中,使用以下语法构建一个表单组来与此表单对话:

Creating the FormGroup

In your component class, in constructor() (this should be before the template renders), use the following syntax to build a form group to talk to this form:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

...
    public readonly myFormGroup: FormGroup;
...
    constructor(private readonly formBuilder: FormBuilder) {
        this.myFormGroup = this.formBuilder.group({
            field1: [],
            field2: [],
            subgroupName: this.formBuilder.group({
                subfield2: [],
            }),
            myRequiredField: ['', Validators.required],
        });
        this.retrieveData();
    }

用数据填写表单

如果您的组件需要在加载时从服务中检索数据,您必须确保它在构建表单后开始传输,然后使用 patchValue() 将数据从您的对象放入FormGroup:

Filling your form with data

If your component needs to retrieve data from a service as it loads, you must make sure it starts the transfer after the form has been built, then use patchValue() to put the data from your object into the FormGroup:

    private retrieveData(): void {
        this.dataService.getData()
            .subscribe((res: SomeDataStructure) => {
                // Assuming res has a structure like:
                // res = {
                //     field1: "some-string",
                //     field2: "other-string",
                //     subgroupName: {
                //         subfield2: "another-string"
                //     },
                // }
                // Values in res that don't line up to the form structure
                // are discarded. You can also pass in your own object you
                // construct ad-hoc.
                this.myFormGroup.patchValue(res);
            });
    }

从表单中获取数据

现在,假设您的用户单击提交,现在您需要从表单中取回数据,然后通过服务将数据 POST 返回到您的 API.只需使用 getRawValue:

Getting data out of the form

Now, say your user clicks submit and now you need to get the data back out of your form and POST it back to your API thru a service. Just use getRawValue:

public onClickSubmit(): void {
    if (this.myFormGroup.invalid) {
        // stop here if it's invalid
        alert('Invalid input');
        return;
    }
    this.myDataService.submitUpdate(this.myFormGroup.getRawValue())
        .subscribe((): void => {
            alert('Saved!');
        });
}

所有这些技术都消除了对任何 [(ngModel)] 绑定的需要,因为表单在 FormGroup 对象中维护了自己的内部模型.

All these techniques eliminate the need for any [(ngModel)] bindings, since the form maintains its own internal model inside the FormGroup object.

这篇关于如何使用反应式表单将表单绑定到 Angular 6 中的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆