Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

Angular 2 - large scale application forms' handling

At the company I’m working for, we’re developing a large scale application with multiple forms, that the user needs to fill in in order to register for our program. When all questions have been answered, then the user reaches a section that sums up all their answers, highlights invalid answers and gives the user the chance to revisit any of the preceding form steps and revise their answers. This logic will be repeated across a range of top-level sections, each having multiple steps/pages and a summary page.

To accomplish this, we have created a component for each separate form step (they are categories like “Personal Details” or “Qualifications” etc.) along with their respective routes and a component for the Summary Page.

In order to keep it as DRY as possible, we started creating a “master” service which holds the information for all the different form steps (values, validity etc.).

import { Injectable } from '@angular/core';
import { Validators } from '@angular/forms';
import { ValidationService } from '../components/validation/index';

@Injectable()
export class FormControlsService {
  static getFormControls() {
    return [
      {
        name: 'personalDetailsForm$',
        groups: {
          name$: [
            {
              name: 'firstname$',
              validations: [
                Validators.required,
                Validators.minLength(2)
              ]
            },
            {
              name: 'lastname$',
              validations: [
                Validators.required,
                Validators.minLength(2)
              ]
            }
          ],
          gender$: [
            {
              name: 'gender$',
              validations: [
                Validators.required
              ]
            }
          ],
          address$: [
            {
              name: 'streetaddress$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'city$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'state$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'zip$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'country$',
              validations: [
                Validators.required
              ]
            }
          ],
          phone$: [
            {
              name: 'phone$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'countrycode$',
              validations: [
                Validators.required
              ]
            }
          ],
        }
      },
      {
        name: 'parentForm$',
        groups: {
          all: [
            {
              name: 'parentName$',
              validations: [
                Validators.required
              ]
            },
            {
              name: 'parentEmail$',
              validations: [
                ValidationService.emailValidator
              ]
            },
            {
              name: 'parentOccupation$'
            },
            {
              name: 'parentTelephone$'
            }
          ]
        }
      },
      {
        name: 'responsibilitiesForm$',
        groups: {
          all: [
            {
              name: 'hasDrivingLicense$',
              validations: [
                Validators.required,
              ]
            },
            {
              name: 'drivingMonth$',
              validations: [
                ValidationService.monthValidator
              ]
            },
            {
              name: 'drivingYear$',
              validations: [
                ValidationService.yearValidator
              ]
            },
            {
              name: 'driveTimesPerWeek$',
              validations: [
                Validators.required
              ]
            },
          ]
        }
      }
    ];
  }
}

That service is being used by all the components in order to set up the HTML form bindings for each, by accessing the corresponding object key and creating nested form groups, as well as by the Summary page, whose presentation layer is only 1way bound (Model -> View).

export class FormManagerService {
    mainForm: FormGroup;

    constructor(private fb: FormBuilder) {
    }

    setupFormControls() {
        let allForms = {};
        this.forms = FormControlsService.getFormControls();

        for (let form of this.forms) {

            let resultingForm = {};

            Object.keys(form['groups']).forEach(group => {

                let formGroup = {};
                for (let field of form['groups'][group]) {
                    formGroup[field.name] = ['', this.getFieldValidators(field)];
                }

                resultingForm[group] = this.fb.group(formGroup);
            });

            allForms[form.name] = this.fb.group(resultingForm);
        }

        this.mainForm = this.fb.group(allForms);
    }

    getFieldValidators(field): Validators[] {
        let result = [];

        for (let validation of field.validations) {
            result.push(validation);
        }

        return (result.length > 0) ? [Validators.compose(result)] : [];
    }
}

After, we started using the following syntax in the components in order to reach the form controls specified in the master form service:

personalDetailsForm$: AbstractControl;
streetaddress$: AbstractControl;

constructor(private fm: FormManagerService) {
    this.personalDetailsForm$ = this.fm.mainForm.controls['personalDetailsForm$'];
    this.streetaddress$ = this.personalDetailsForm$['controls']['address$']['controls']['streetaddress$'];
}

which seems like a code smell in our inexperienced eyes. We have strong concerns how an application like this will scale, given the amount of sections we'll have in the end.

We’ve been discussing different solutions but we can’t come up with one that leverages Angular’s form engine, allows us to keep our validation hierarchy intact and is also simple.

Is there a better way to achieve what we’re trying to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I commented elsewhere about @ngrx/store, and while I still recommend it, I believe I was misunderstanding your problem slightly.

Anyway, your FormsControlService is basically a global const. Seriously, replace the export class FormControlService ... with

export const formControlsDefinitions = {
   // ...
};

and what difference does it make? Instead of getting a service, you just import the object. And since we're now thinking of it as a typed const global, we can define the interfaces we use...

export interface ModelControl<T> {
    name: string;
    validators: ValidatorFn[];
}

export interface ModelGroup<T> {
   name: string;
   // Any subgroups of the group
   groups?: ModelGroup<any>[];
   // Any form controls of the group
   controls?: ModelControl<any>[];
}

and since we've done that, we can move the definitions of the individual form groups out of the single monolithic module and define the form group where we define the model. Much cleaner.

// personal_details.ts

export interface PersonalDetails {
  ...
}

export const personalDetailsFormGroup: ModelGroup<PersonalDetails> = {
   name: 'personalDetails$';
   groups: [...]
}

But now we have all these individual form group definitions scattered throughout our modules and no way to collect them all :( We need some way to know all the form groups in our application.

But we don't know how many modules we'll have in future, and we might want to lazy load them, so their model groups might not be registered at application start.

Inversion of control to the rescue! Let's make a service, with a single injected dependency -- a multi-provider which can be injected with all our scattered form groups when we distribute them throughout our modules.

export const MODEL_GROUP = new OpaqueToken('my_model_group');

/**
 * All the form controls for the application
 */
export class FormControlService {
    constructor(
        @Inject(MMODEL_GROUP) rootControls: ModelGroup<any>[]
    ) {}

    getControl(name: string): AbstractControl { /etc. }
}

then create a manifest module somewhere (which is injected into the "core" app module), building your FormService

@NgModule({
   providers : [
     {provide: MODEL_GROUP, useValue: personalDetailsFormGroup, multi: true}
     // and all your other form groups
     // finally inject our service, which knows about all the form controls
     // our app will ever use.
     FormControlService
   ]
})
export class CoreFormControlsModule {}

We've now got a solution which is:

  • more local, the form controls are declared alongside the models
  • more scalable, just need to add a form control and then add it to the manifest module; and
  • less monolithic, no "god" config classes.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...