DEV Community

Ushmi Dave
Ushmi Dave

Posted on

3 1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay