Angular strongly typed reactive forms

前端 未结 3 1571
再見小時候
再見小時候 2021-02-14 01:57

I\'m looking to refactor a large set of components in my Angular project to have strongly typed FormGroups, FormArrays, and FormControls.

I\'m just looking for a good wa

相关标签:
3条回答
  • 2021-02-14 02:37

    The solution I ended up using was a library I found called ngx-strongly-typed-forms

    It enables you to have strongly typed FormControls, FormGroups, and FormArrays. There are some limitations but it's definitely helped a lot in my project.

    You can see the documentation at https://github.com/no0x9d/ngx-strongly-typed-forms

    0 讨论(0)
  • 2021-02-14 02:41

    The most elegant solution is leveraging TypeScript declaration files (*.d.ts) to introduce generic interfaces extending the standard form classes like AbstractControl, FormControl, etc. It doesn’t introduce any new functionality and has no footprint in the compiled JavaScript, but at the same time enforcing strong type checking.

    It was suggested by Daniele Morosinotto in March this year and there are talks now to include it in Angular 9.

    Adopting the solution is straightforward:

    1. Download TypedForms.d.ts from this gist and save it as src/typings.d.ts in your project (Angular 6+ already knows how to use this file).
    2. Start using the new types (FormGroupTyped<T>, FormControlTyped<T>, etc.) whenever you need a strong type validation (see examples in that gist or stackblitz).

    For more information, check out a blog post analysing available solutions for strongly typed forms.

    0 讨论(0)
  • 2021-02-14 02:43

    I had a similar issue and this was my solution. I really only cared about the type of the 'value' of the form not the form itself. It ended up looking something like this.

    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) ] ],
      });
    }
    
    ...
    

    Then in the template submit the value

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

    Now you can add a type to the submit function

    onSubmit(userForm: UserFormValue) {
       ...
    }
    

    It's not perfect but has been good enough for my use cases. I really wish there was like this.

    userForm: FormGroup<UserFormValue>

    0 讨论(0)
提交回复
热议问题