角强型反应形式

时间:2019-03-07 21:59:34

标签: angular typescript angular-reactive-forms reactive-forms

我希望在Angular项目中重构大量组件,使其具有强类型的FormGroups,FormArrays和FormControls。

我只是在寻找一种实现强类型反应式的好方法。谁能根据自己的经验提供建议/建议?

谢谢。

编辑:

通过强类型进行澄清,我的意思是当前我在创建FormGroup或FormArray时无法指定其中的实际表单的结构。当我将此表单传递给应用程序中的各个组件时,我感到维护起来更加困难。

4 个答案:

答案 0 :(得分:2)

对于那些想要其他解决方案的人。我发现 this article 在谈论角形式的强类型。以下是我的总结。

interface Person {
  name: string;
  email: string
}

// Controls in a form group that would emit a Person as it's value
type PersonControls = { [key in keyof Person]: AbstractControl };
type PersonFormGroup = FormGroup & { value: Person, controls: PersonControls };

export class MyFormComponent {
  form = new FormGroup({
    name: new FormControl(),
    email: mew FormControl()
  } as PersonControls) as PersonFormGroup;

  init() {
    const name = this.form.controls.name; // strong typed!
  }
}

答案 1 :(得分:0)

最优雅的解决方案是利用TypeScript声明文件(*.d.ts)引入通用接口,以扩展诸如AbstractControlFormControl等标准表单类。它不引入任何新的功能,并且在已编译的JavaScript中没有占用空间,但同时强制执行强类型检查。

它是suggested由Daniele Morosinotto于今年3月提出,there are talks现在已将其包含在Angular 9中。

采用解决方案非常简单:

  1. this gist下载TypedForms.d.ts,并将其另存为src/typings.d.ts在您的项目中(Angular 6+已经知道如何使用此文件)。
  2. 每当需要强类型验证时就开始使用新类型(FormGroupTyped<T>FormControlTyped<T>等)(请参见that giststackblitz中的示例)。

有关更多信息,请查看blog post分析强类型表单的可用解决方案。

答案 2 :(得分:0)

我最终使用的解决方案是library I found called ngx-strongly-typed-forms

它使您可以具有强类型的FormControls,FormGroups和FormArrays。有一些限制,但在我的项目中肯定有很大帮助。

您可以在https://github.com/no0x9d/ngx-strongly-typed-forms

上查看文档。

答案 3 :(得分:0)

我遇到了类似的问题,这就是我的解决方案。我真的只关心表单的“值”的类型,而不是表单本身。最终看起来像这样。

export interface UserFormValue {
  first_name: string
  last_name: string
  referral: string
  email: string
  password: string
}
...

ngOnInit() {
  this.userForm = this.fb.group({
    first_name: [ '', Validators.required ],
    last_name: [ '', Validators.required ],
    referral: [ '' ],
    email: [ '', [ Validators.required, Validators.email ] ],
    password: [ '', [ Validators.required, Validators.minLength(8) ] ],
  });
}

...

然后在模板中提交值

<form [formGroup]="userForm" (ngSubmit)="onSubmit(userForm.value)">
   ...
</form>

现在您可以将类型添加到提交功能

onSubmit(userForm: UserFormValue) {
   ...
}

这并不完美,但对于我的用例来说已经足够了。我真的希望像这样。

userForm: FormGroup<UserFormValue>

相关问题