A little trick with Angular forms and directives 🃏

Imagine having a form that you want to use at multiple places inside your application. The form will have the same layout but the validation will be different.

In our case, this form is used in a multi-step procedure and in each step of the procedure the form gets more restrictive. Can you keep it DRY? We had this problem and came up with the following solution.

The form

As an example let's take a simple form, we have a person with a name, contact info, and allergies.
In the beginning, only the name is required. Later on, we're going to require the rest of the person's info.

To be sure that the directive will have the PersonComponent injected, we have to make the directive specific for the person form. To accomplish this, we can use the component's selector as a prefix and append the directive's name to it, person[stage-one]. By doing this, you can only use the directive if the directive is added as an attribute on the person component.
Because the form on the person component is set to public, we can access the form from within our directive. If we have access to the form, we have access to the form fields and their validators.