5 Reasons to Choose Model Based Reactive Forms Using RxWeb
Tags: angular, rxweb, webdev, typescript
Published: 2020-03-31 17:41:11

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](https://dev.to/ushmidave/simplified-angular-reactive-forms-2l47) 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
```js
import { prop } from   "@rxweb/reactive-form-validators"   

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

        @prop() 
       lastName: string;		
}
```

Component  
```js
    export class UserComponent implements OnInit {
    userFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder    ) { }

    ngOnInit() {
        this.userFormGroup = this.formBuilder.formGroup(User);
    }
}
```
The complete example is available on [stackblitz](https://stackblitz.com/angular/dymkkragqbg?file=src%2Fapp%2Fprop-add.component.ts)

# 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. 

```js
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);
        })
```
The complete example is available on [stackblitz](https://run.stackblitz.com/api/angular/v1?file=src/app/alpha-dynamic.component.ts)

# 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.

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

@prop()
userName:string;

@prop()
password:string;

@prop()
cityName:string;

@prop()
countryName:string;

@prop()
areaName:string;
}
```      
The complete example is available on [stackblitz](https://run.stackblitz.com/api/angular/v1?file=src/app/model-element.component.ts)    

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

```js
export class FormField{
  
  @prop()
  action:string;

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

  @required()
  firstName:string;
}
```
The complete example is available on [stackblitz](https://stackblitz.com/angular/remjeyjgqym?file=src%2Fapp%2Ferror-add.component.ts)  

# 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`.

```js
   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[];

}
```
The complete example is available on [stackblitz](https://run.stackblitz.com/api/angular/v1?file=src/app/bind-complete.component.ts)  

# 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.

```js
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> {

  }
```
The complete example is available on [stackblitz](https://run.stackblitz.com/api/angular/v1?file=src/app/bind-complete.component.ts)  

# Conclusion
All the above features can be achieved using [@rxweb](https://www.npmjs.com/package/@rxweb/reactive-form-validators) 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](https://gitter.im/rxweb-project/rxweb)