DEV Community

Ushmi Dave
Ushmi Dave

Posted on

Choose your strategy globally to bind error messages in angular reactive dynamic forms

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

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 { }

Enter fullscreen mode Exit fullscreen mode

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

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}});
  }
}
Enter fullscreen mode Exit fullscreen mode

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

{
            name:"firstName",
            type:"text",
            ui:{
              "label":"FirstName"
            },
            validators:{
              required:true
            }
        },
        {
            name:"lastName",
            type:"text",
            ui:{
               "label:"LastName"
            },
            validators:{
              required:true
            }
        }
Enter fullscreen mode Exit fullscreen mode

(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:

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);          
    }
}
Enter fullscreen mode Exit fullscreen mode

(6) html Implementation :

<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>
Enter fullscreen mode Exit fullscreen mode

Please refer the working example

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

Top comments (0)