我的场是有Angular 的,在我的场被直接绑定到[(ngModel)]之前.现在已经弃用了(不能用于被动表单),我不知道如何用表单值更新我的模型.我可以使用form.getRawValue(),但这需要我用新的rawValue替换当前模型——这是不可取的,因为我的主模型比本地表单模型更大,字段更多.

有什么 idea 吗?

推荐答案

不要用[(ngModel)]!react 型更好.它们使手动ngModel绑定过时,它们有一些非常好的内置功能,我将在本回答中介绍其中的几个.

Binding to the form

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

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

(100, 101, 102, 103, and 104 are all arbitrary control and control group names that correspond to parts of your form, see below when creating the 105 object.)

在模板中,对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 }}

Creating the 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();
    }

Filling your form with data

如果组件在加载时需要从服务中检索数据,则必须确保它在生成表单后开始传输,然后使用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);
            });
    }

Getting data out of the form

现在,假设你的用户点击提交,现在你需要把数据从你的表单中取出来,并通过一个服务将其返回给你的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对象中维护自己的内部模型.

Typescript相关问答推荐

如何用不同的键值初始化角react 形式

TypeScript类型不匹配:在返回类型中处理已经声明的Promise Wrapper

不推荐使用Marker类-Google map API警告

如何在Angular 12中创建DisplayBlock组件?

返回具有递归属性的泛型类型的泛型函数

为什么有条件渲染会导致material 自动完成中出现奇怪的动画?

是否可以从函数类型中创建简化的类型,go 掉参数中任何看起来像回调的内容,而保留其余的内容?

分解对象时出现打字错误

如何在深度嵌套的Reaction路由对象中隐藏父级?

已解决:如何使用值类型限制泛型键?

如何将定义模型(在Vue 3.4中)用于输入以外的其他用途

为什么Typescript不能推断类型?

Angular:ngx-echart 5.2.2与Angular 9集成错误:NG 8002:无法绑定到选项,因为它不是div的已知属性'

React router 6(数据路由)使用数据重定向

类型脚本-在调用期间解析函数参数类型

为什么TS2339;TS2339;TS2339:类型A上不存在属性a?

如何键入对象转换器

带有';的类型脚本嵌套对象可选属性错误满足';

React-跨组件共享功能的最佳实践

Next 13 + React 18 createContext 类型的构建问题