Choose your strategy globally to bind error messages in angular reactive dynamic forms 
Tags: angular, rxweb
Published: 2019-09-04 17:10:45

while using angular validations we are in need of binding errorMessages based upon application need,like (1)OnSubmit, (2)OnDirty, (3)OnTouched based upon that we usually bind `errorMessages` using multiple *ngIf conditions or by configuring it in the component.

But how about globally defining errorMessage strategy throughout the application,
In this article we will see how to use the same error message strategy throughout the application.

It can achieved by following below steps:

(1) Install two packages in the project, both package installation command is mentioned below:

> npm install @rxweb/reactive-dynamic-forms

This package is used for building the model-driven dynamic forms.
For more information on reactive dynamic forms, Please refer this [article] (https://medium.com/@oojhaajay/new-way-to-build-dynamic-reactive-form-in-angular-c50978c66d99) on new way to build angular dynamic forms.

> npm install @rxweb/reactive-form-validators 

(2) Now we have to register the `RxReactiveDynamicFormsModule` and `RxReactiveFormsModule` module in the root module.

```js
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { FormsModule,ReactiveFormsModule } from '@angular/forms'; 

import { RxReactiveDynamicFormsModule } from "@rxweb/reactive-dynamic-forms"
import { RxReactiveFormsModule } from "@rxweb/reactive-form-validators"

@NgModule({
  imports:      [ BrowserModule, 
                    FormsModule,ReactiveFormsModule,
                    RxReactiveFormsModule,RxReactiveDynamicFormsModule 
                ],
  declarations: [  ],
  bootstrap:    [  ]
})
export class AppModule { }

```
  
(3) You need to configure global message and its strategy in app component :

```js
import { Component,OnInit } from '@angular/core';
import { ReactiveFormConfig } from '@rxweb/reactive-form-validators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {

  ngOnInit(){
    //if you want to apply global configuration then use below code. 
    ReactiveFormConfig.set({"validationMessage":{"required":"This field is 
  required"},
  "reactiveForm":{"errorMessageBindingStrategy":1}});
  }
}
```
> The by default errorMessageBindingStrategy is ErrorBindingStrategy.none.

The errorMessageBindingStrategy can be 
### ErrorBindingStrategy.none :
 There is no condition to bind the error message, The error messages will be bind as soon as the FormControl is invalid.

### ErrorBindingStrategy.onSubmit : 
Whenever the RxFormGroup property submitted is true then the invalid FormControl error messages will be bind.

### ErrorBindingStrategy.onDirty: 
Once the FormControl is dirty, after that invalid FormControl error messages will be bind accordingly.

The FormControl should be marked as dirty using markAsDirty()

### ErrorBindingStrategy.onTouched:
Once the FormControl is touched, after that invalid FormControl error messages will be bind accordingly.

The FormControl should be marked as touched using markAsTouched()

### ErrorBindingStrategy.onDirtyOrTouched:
Once the FormControl is Dirty or Touched, after that invalid FormControl error messages will be bind accordingly. 

(4) let's start building json, suppose we have two fields firstName and lastName and we want to apply required validation 

```js
{
            name:"firstName",
            type:"text",
            ui:{
              "label":"FirstName"
            },
            validators:{
              required:true
            }
        },
        {
            name:"lastName",
            type:"text",
            ui:{
               "label:"LastName"
            },
            validators:{
              required:true
            }
        }
```

(5) We have to import `RxDynamicFormBuilder`, `DynamicFormBuildConfig` and `DynamicFormConfiguration` in the component. The RxDynamicFormBuilder the property we define in the constructor for resolving the dependencies.
We also import server_data.ts file in the component.
Here is the code of the component:
```js
import { Component, Input,OnInit } from '@angular/core';
import { RxDynamicFormBuilder,DynamicFormBuildConfig } from "@rxweb/reactive-dynamic-forms"
import {SERVER_JSON} from './server-json';


@Component({
  selector:"dynamic-validation",
  templateUrl:'./dynamic-validation.component.html'
})
export class DynamicValidationComponent implements OnInit  {
  
    dynamicFormBuildConfig:DynamicFormBuildConfig;   

    formData:any[] = SERVER_JSON;


    uiBindings:string[] = ["firstName","lastName"];

    constructor(private dynamicFormBuilder:RxDynamicFormBuilder){}

    ngOnInit(){
            this.dynamicFormBuildConfig = this.dynamicFormBuilder.formGroup(this.formData);          
    }
}
```

(6) html Implementation :
```js
<form [formGroup]="dynamicForm.formGroup">
    <div viewMode="basic" [rxwebDynamicForm]="dynamicForm" [uiBindings]="uiBindings">
    </div>
    <button [disabled]="!dynamicForm.formGroup.valid" type="submit" class="btn btn-primary">Submit</button>
</form>
``` 

Please refer the working [example](https://stackblitz.com/edit/angular-rjkntp-hco8zy?file=src/app/dynamic-validation.component.ts)

If you have any query or suggestion, Please comment below.