Sitemap

Formio in angular

5 min readOct 10, 2024

--

What’s FormIO?

Form.io is a powerful form management application that streamlines the creation of dynamic forms via an intuitive drag-and-drop interface. It automatically generates a JSON for each form, enabling easy integration into web applications through the Formio renderer component. This facilitates seamless incorporation of form functionalities into your applications, providing both flexibility and user-friendliness for managing and collecting data effectively.

Getting Started

Step 1 —

Install the Package

To integrate Form.io into your Angular application, you’ll need to use the @formio/angular library. Run the command shown below to install the library in your angular application:

npm install @formio/angular

Step 2 —

Import Formio Module

If you are using Standalone component import it in the same component ,If not , Import FormioModule in the app.module file.

Step 3 —

Adding Form Builder to create form

The @formio/angular library has a form-builder component, which allows you to present a user-friendly drag-and-drop interface for creating forms. we can include it in your component’s template file.

<form-builder
[form]="form"
(change)="handleChangeClick($event)"
></form-builder>

The form is initialized with a default JSON structure of type FormioForm, serving as a foundation for the form builder. The formJSON variable provides the initial data for customization and development. Below the typescript code of form builder component.

import { FormioForm } from '@formio/angular';
..

@Component({
...
...
})
export class BuildFormComponent {
form: FormioForm = { display: 'form', components: [] };

handleChangeClick(event:any) {
console.log(event.form);
}
}

The Form.io form builder allows the creation of both single-page and multi-paged forms, with the layout type specified through the display property in the form JSON.

a. Use display: ‘form’ for single page forms as shown in the example below.

Single page form
Single page form

b. To create a multi-paged form, set the display property in the form JSON to ‘wizard’. This enables the form builder interface to allow the addition of new pages, as shown below:

Multi page form

We can add input fields to the form using the drag-and-drop interface, which generates a JSON Schema. This schema can be accessed through the change event emitted by the form builder. You can then save this schema in your application’s state and persist it in the database.

Step 4: Render—

Now that the form has been created and we have the corresponding JSON, we can render it . This can be achieved by utilizing the Formio component, as shown below:

<formio
[form]="form"
[submission]="submission "
(change)="handleChangeClick($event)"
(nextPage)="handleNextClick($event)" //for multi-paged forms
(prevPage)="handlePrevClick($event)" //for multi-paged forms
[readOnly]="readOnly"
(submit)="handleSubmit($event)"
></formio>

a. Form: It accepts the JSON Schema generated by the form builder, defining the form’s structure and components.

Get Swarooplenka’s stories in your inbox

Join Medium for free to get updates from this writer.

b. Submission: This attribute pre-populates the form with default values or saved user values from database, allowing for initial data setup.

c. Change: The change event is triggered whenever a user modifies their response, or while filling the form ,it emits the details in JSON format enabling the data capture.

d. NextPage and prevPage: These events are triggered when users click the “Next” or “Previous” buttons in multi-paged forms, facilitating step-by-step navigation.

e. ReadOnly: if set to true, this attribute disables whole form, preventing changes and provides a read-only view of the form.

f. Submit : The submit output event can be used as a submit option in the formio, when user click on submit option in formio, this is triggered and we can get all the user response corresponding to form in JSON.

@Component({
...
...
})
export class ViewFormComponent {
form: FormioForm = { display: 'form', components: [] };
submission: { data: any } = { data: null };
readOnly: boolean = false;

handleChangeClick(event) {
this.submission = { data: event.data };
// submissions should have the key as “data” and value as userdata
// { data : userData}
}

handleNextClick = (e) => {
console.log(e);
};

handlePrevClick = (e) => {
console.log(e);
};

handleSubmit(e) {
console.log(e);
}

Additional Features in Formio :

The formio provides a options for file handling , for internationalization and for error handling etc, below is the list of options.

export interface FormioOptions {
errors?: ErrorsOptions;
alerts?: AlertsOptions;
alertsPosition?: AlertsPosition;
disableAlerts?: boolean;
i18n?: object;
fileService?: object;
hooks?: FormioHookOptions;
sanitizeConfig?: any;
}

A. File Handling :

We can provide our own file service as option in formio or we can define a url in the form builder itself for the file component , while creating the form.

We need to always initialize formio Options in constructor only otherwise it won’t work.

//Parent Component
import { FormioOptions } from @formio/angular;

options: FormioOptions;

constructor(private FileService: FileService) {
this.options.fileService = FileService;
}

// The file Service should consist of 3 methods, otherwise file handling won’t work.

export class FileService {

constructor() {
}
async uploadFile(storage, file, fileName, dir, evt, url, options) {

}

async downloadFile(fileInfo, options?) {

}

async deleteFile(fileInfo) {

}
}

B. Formio have a output event called ready , when the form is ready it emits this event.

Using this we can check the validity of the form or set a specific page if it is a multi page form, etc.

onFormReady = (e: FormioComponent) => {
console.log (e);
const wizard = e.formio;
const submission = {data: userData};
wizard.checkValidity(submission); // accepts the user submission object
// To set a Specific page in multi page form
wizard.setPage(0) // follows 0 based Indexing

}

C. we can refresh the form using the refresh Input

refreshEmitter: EventEmitter<any> = new EventEmitter<any>();

handleRefreshClick = () => {
this.refreshEmitter.emit({
submission: {
data: {},
},
});
};

D. For Internationalization support, in the formio options we have support for i18n

this.options.i18n = {
jp : { // japanese
"required": "必須項目です",
},
hi : { // hindi
"required": "आवश्यक है",
}
// key is the value present in the formio
// value is the message to be displayed
}

For more on Internationalization see : Github

The Final Formio Renderer component with all Inputs and Outputs :

  <formio
[form]="form"
[submission]="submission ? submission : { data: null }"
(ready)="onFormReady($event)"
(change)="handleChangeClic($event)"
(submit)="onSubmit()"
[refresh]="refreshEmitter"
[options]="options"
(nextPage)="handleNextClick($event)"
(prevPage)="handlePrevClick($event)"
></formio>

Conclusion:

In this article, we saw how to build dynamic forms in Angular using formio. Formio offers an efficient alternative, allowing developers to easily create and render dynamic forms through a user-friendly form builder interface. This capability simplifies both the development and maintenance processes.

--

--