Building reactive forms with RxFormMapper

What’s RxFormMapper?

RxFormMapper is a framework developed for angular and allows you to convert, by annotation, classes into reactive form and vice versa.

When to use RxFormMapper?

Sometimes you want to transform the classes you have into reactive forms, for example you have a user model that you want to have filled out by a form:

export class User {
name: string;
surname: string;
age: number;
}
new FormGroup(
name: new FormControl(user.name),
surname: new FormControl(user.surname),
age: new FormControl(user.age),
);
export class User {	@FormControl()
name: string;
@FormControl()
surname: string;
@FormControl()
age: number;
}

Why use RxFormMapper?

RxFormMapper speed up your form development avoiding redundant boilerplate in your code. The most important benefits are:

  • Zero configuration: through annotations removes the boilerplate for creating and assigning forms.
  • Dependency Injection: RxFormMapper take advantage from Angular DI container in order to resolves validators and custom mappers.
  • Custom mappers: If you want to create custom forms for specific fields, you can do it simple by @CustomControl decorator.

Let’s start writing code

Install npm package

npm i rx-form-mapper --save
npm i reflect-metadata --save

Import the component modules

Import RxFormMapperModule in your AppModule

Define your model

Annotate it

RxFormMapper allow you to specify through annotations the type of AbstractControl for each field in your model, specifically: FormControl, FormGroup and FormArray.

Wait... AsyncValidators? How to inject services?!

Don’t panic: RxFormMapper automatically resolves all validators registered inside the Angular container for you! 😉

Build your form

Conclusion

RxFormMapper is a great tool that allows you to create reactive forms in a simple and declarative way through the annotations, allowing you to focus on your features.
This type of framework is particularly suitable for crud-based applications as it drastically reduces the code to maintain.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store