5 Reasons to Choose Model Based Reactive Forms Using RxWeb

ushmidave

Ushmi Dave

Posted on March 31, 2020

5 Reasons to Choose Model Based Reactive Forms Using RxWeb

Enterprise applications build in angular are not just data binding components, they involve lots of new business rules, use cases implemented everyday with a lot of increasing complexity to fulfill the application needs.

To construct a modular angular application does not only require inserting and reading data, It also involves managing data integrity, validations, coding consistency, reuse-ability with the best efficient way out there Here are some benefits of using model based angular reactive forms approach

For detailed information on how to create a model based reactive form visit this article

Simplified Components

Components are tend to process for performing various actions on the data which involves large forms including formArrays, nested form groups and complex types of validations which involve a lot of custom business logic to be written which results to lengthy and clumsy code of the component. While using model driven approach all these things are maintained in the model class and then the props are grouped in the form as a control

Model

import { prop } from   "@rxweb/reactive-form-validators"   

export class User {
    @prop() 
    firstName: string;

        @prop() 
       lastName: string;        
}
Enter fullscreen mode Exit fullscreen mode

Component

    export class UserComponent implements OnInit {
    userFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder    ) { }

    ngOnInit() {
        this.userFormGroup = this.formBuilder.formGroup(User);
    }
}
Enter fullscreen mode Exit fullscreen mode

The complete example is available on stackblitz

Server Rule Validations

There are several rules which come from the database and there is a need to apply them dynamically whenever needed in the form which is also known as dyamic validation.

This Dynamic validation is executed on the basis of json passed in the formBuilderConfiguration which comes under RxFormBuilder of reactive-form-validators.

let formBuilderConfiguration = new FormBuilderConfiguration();
        this.http.get('assets/dynamic.json?v=' + environment.appVersion).subscribe(dynamic => {
            formBuilderConfiguration.dynamicValidation = JSON.parse(JSON.stringify(dynamic));
            this.addressInfoFormGroup = this.formBuilder.formGroup(user,formBuilderConfiguration);
        })
Enter fullscreen mode Exit fullscreen mode

The complete example is available on stackblitz

Easier Validations

Validations have a lot of use-cases which may not be executed by the in-built angular validations. simple forms may need to apply some validations on all the fields of the form

For validating all the properties using one decorator @model is used.

@model([{
    propNames: [":all:"], validationConfig: { required: true } }])
export class User{

@prop()
userName:string;

@prop()
password:string;

@prop()
cityName:string;

@prop()
countryName:string;

@prop()
areaName:string;
}
Enter fullscreen mode Exit fullscreen mode

The complete example is available on stackblitz

For displaying error messages based upon some action @error is used.

export class FormField{

  @prop()
  action:string;

  @error({conditionalExpression:function(control:AbstractControl){ return 
  this.action === "submit"}})

  @required()
  firstName:string;
}
Enter fullscreen mode Exit fullscreen mode

The complete example is available on stackblitz

On Demand Validation Configuration

While developing large forms, we have multiple needs to validate the FormControl. For that we are going to write the custom business logic a lot to manage the complex scenarios.

The benefit of using this is don't have worry about when this validator will call, this will be called whatever properties you have used in the dynamicConfig function. Those thing the framework automatically take cares of it.
This is implemented using dynamicConfig.

   export class User {

    @prop()
    purchasePrice: number;

    @minNumber({
        dynamicConfig: (x, y) => {
            const minimumPrice = (x.purchasePrice * 1) + (x.purchasePrice * 30 / 100);
              return { value: minimumPrice, message: `Resale price must be at least 30% more than Purchase price. Minimum resale price should be ${minimumPrice}` };
          }
    })
    resalePrice: any[];

}
Enter fullscreen mode Exit fullscreen mode

The complete example is available on stackblitz

Manage generic nested level Properties

Here we discuss about very common scenario in the class object properties. Like say for example we have student model and we would like to store the information of Subjects and Courses in which Subjects is propArray which contains generic property subjectDetails in this we need to pass parameter T and it should work based on the instance of the created object.

export class Course{
    @prop()
    courseId : number;
  }
  export abstract class Student<T> extends Course {
      @propArray() SubjectDetails: T[];
  }

  export class Subjects {
      @prop()
      enrollmentNumber: number;
  }

  export class StudentCourse extends Student<Subjects> {

  }
Enter fullscreen mode Exit fullscreen mode

The complete example is available on stackblitz

Conclusion

All the above features can be achieved using @rxweb which contains more number of validations and a lot more advance reactive features.

Feel free to share your feedback, you can also share your suggestion on gitter

💖 💪 🙅 🚩
ushmidave
Ushmi Dave

Posted on March 31, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related