Angular strongly typed reactive forms

前端 未结 3 1570
再見小時候
再見小時候 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: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

    ...

    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

提交回复
热议问题