One of the mostly used components in web applications are forms. Thus, it is of prior importance to componentize the layout and the expected behavior of the potentially numerous forms in our applications.
Here there are some common concerns about forms in a web application.
- Layout between fields and labels.
- When and where validation messages should appear.
- Layout of form buttons.
I will try to cover all of the above concerns by presenting an example, keeping in mind all of the tools which angular provides to us.
Beyond the fact that angular makes our lives easier by providing all those great modules, such as
ReactiveFormsModule, it’s our responsibility to keep our code dry and clean by making the right use of them. There are times when forms require lots of inputs, which drives us creating huge and messy templates.
For that reason we are going to wire up all of those common layout and behavior in
directives. Let me introduce you those by starting of the inner to outer.
FormErrorMessagesComponent is responsible for rendering the validation messages of the form. Works similarly, to the AngularJS’
It takes one and only input, the errors of the form.
FormFieldComponent takes as inputs:
labelof the input field
errorsto pass them to the
verticalattribute which defines whether the field and the label will be on the same line or not.
Moreover, it projects the input field in its template.
No inputs for this component, which is primarily used for aligning the projected buttons left or right.
FormLayoutComponent holds zero business logic and it mainly scopes all the styles which define part of the layout for the rest of the components. That means that it will work as a wrapper for the other components.
SubmittedClassDirective adds css class when form is submitted or removes it when form gets cleared. This will allow us to hide or show the error messages just by css.
Putting all those pieces together leads to something like that:
If you would like to dig in here’s the snippet.
Here are some benefits of this approach:
- Clean markup
- Dry code
The previously presented example demonstrates some of the capabilities of the angular ecosystem out of which we can benefit when we deal with forms.