Refer to FormBuilder Members in a Strongly Typed list in Angular 8

前端 未结 1 1424
陌清茗
陌清茗 2021-01-17 06:26

We are trying to refer to Formcontrols in a Formbuilder in a strongly typed way. Currently have a Formbuilder with 20+ fields, and need to toggle off validators and visibili

相关标签:
1条回答
  • 2021-01-17 06:45

    I don't know if I'm understanding the problem 100%, but I did run into the issue of FormBuilder not being strongly typed. Posting my solution (just example code) here in case it's useful:

    type FormConfig<T> = {
    [K in keyof Required<T>]:
        | [
                T[K] | '',
                (ValidatorFn | ValidatorFn[] | ValidationErrors)?,
                (AsyncValidatorFn | AsyncValidatorFn[] | ValidationErrors)?,
                AbstractControlOptions?
          ]
        | AbstractControl;
    };
    
    const customerFormConfig: FormConfig<Customer> = {
        name: ['', Validators.required],
        emailAddress: ['', Validators.email],
    }
    
    form = this.formBuilder.group(customerFormConfig);
    

    The trick here is that if any properties change in the Customer class, then customerFormConfig will throw a build error until you update the "formConfig".

    I hope this helps.

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