繁体   English   中英

如何使用反应式表单将表单绑定到 Angular 6 中的模型?

[英]How can I bind a form to a model in Angular 6 using reactive forms?

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

有任何想法吗?

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

绑定到表单

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

<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>

field1field2subgroupNamesubfield2 ,和myRequiredField都是任意的控制和控制组名称相应于你的形式的部分,看到在创建时下面FormGroup对象)。

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

{{ 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() (这应该在模板渲染之前),使用以下语法来构建一个表单组来与这个表单对话:

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

    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

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对象中维护着自己的内部模型。

正如Angular Documentation 中更完整的解释,使用反应式表单,您不会将表单直接绑定到您的模型。 相反,您使用 FormBuilder 来构建一个 FormGroup 对象(本质上是“表单”),该对象将维护它自己的模型。 在构建过程中,您有机会在表单中设置初始值,这通常会在您的模型中进行。

然后将模板中的表单控件绑定到表单的模型。 用户与表单控件的交互会更新表单的模型。

当您准备好对表单数据执行某些操作时(例如“提交”表单),您可以使用 FormGroup 的 value 属性或 getRawValue() 方法从表单字段中获取值 - 这两种行为不同,请参阅有关详细信息的文档。

一旦你从形式获取值,如果你愿意,你可以更新表单中的数值模型

您可以订阅表单组中的更改并使用它来更新您的模型。 但这并不安全。 因为您必须确保您的表单字段与模型字段匹配或添加验证模型中的字段存在。

bindModelToForm(model: any, form: FormGroup) {
    const keys = Object.keys(form.controls);
    keys.forEach(key => {
        form.controls[key].valueChanges.subscribe(
            (newValue) => {
                model[key] = newValue;
            }
        )
    });
}

我的服务的完整代码:
referenceFields - 意味着如果您有像student: { name, group }这样的复杂字段student: { name, group }其中group是引用模型,并且您只需要能够从此模型中获取 id:

import { Injectable } from '@angular/core';
import { FormGroup } from "@angular/forms";

@Injectable({
    providedIn: 'root'
})
export class FormService {

    constructor() {
    }

    bindModelToForm(model: any, form: FormGroup, referenceFields: string[] = []) {
        if (!this.checkFieldsMatching(model, form)) {
            throw new Error('FormService -> bindModelToForm: Model and Form fields is not matching');
        }
        this.initForm(model, form);
        const formKeys = Object.keys(form.controls);
        formKeys.forEach(key => {
            if (referenceFields.includes(key)) {
                form.controls[key].valueChanges.subscribe(
                    (newValue) => {
                        model[key] = newValue.id;
                    }
                )
            } else {
                form.controls[key].valueChanges.subscribe(
                    (newValue) => {
                        model[key] = newValue;
                    }
                )
            }
        });
    }

    private initForm(model: any, form: FormGroup) {
        const keys = Object.keys(form.controls);
        keys.forEach(key => {
            form.controls[key].setValue(model[key]);
        });
    }

    private checkFieldsMatching(model: any, form: FormGroup): boolean {
        const formKeys = Object.keys(form.controls);
        const modelKeys = Object.keys(model);
        formKeys.forEach(formKey => {
            if (!modelKeys.includes(formKey)) {
                return false;
            }
        });
        return true;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM