Expanding collapsible elements on form errors

Suraj Poddar
Hevo Data Engineering
2 min readAug 27, 2020

When we are building forms in Angular, there can be scenarios where we need to group various input elements. And depending on the requirements these groups can be collapsible as well.

If there are such collapsible elements, we would like them to expand automatically when users try to submit the form if they contain inputs that are invalid.

Let's check out how we can do this in a declarative manner.

Let’s create a directive named expandOnFormError which we will be applying to the elements that are collapsible.

Our directive expects a single input property that implements a standard interface to expand or collapse an element.

Let us assume that the expandable object implements the following interface.

Next, we need to know when a form is submitted. To do this we can use Angular’s DI system to inject the existing instance of NgForm into our directive and subscribe to ngSubmit observable on the same.

Whenever, ngSubmit fires we can check if there is any invalid form control as children of the element on which this directive is applied, and call expand method on the object that provides the expandable interface.

We can use ContentChildren decorator to get a reference to the children form controls.

Following is an example implementation of the directive.

Our implementation works on any object that implements the interface IExpandable . Here we are using a directive called hdExpand that implements this interface.

In the real world you might end up using a 3rd Party library for providing the expand/collapse functionality, and it might not implement our standard interface.

With some modifications to our code, we can make this work for such cases as well. For example, the directive can expect any object as its input property and call the expand method on an adapter instead of the exact object. On top of this, we can use DI to provide a factory that returns the correct Adapter for a given object that implements expand/collapse logic.

If you don’t rely on the inbuilt form submission, you can still use this directive. All you need to do is to emit ngSubmit event on the ngForm directive manually.

--

--