DEV Community

Ajay Ojha
Ajay Ojha

Posted on

7 1

Unique value validation in FormArray of Angular

cross posted to medium.com

Here, we discuss the approach of unique value validation on FormControl inside the FormArray.

we build a Job Application Form, where the user can enter about his name and skills. Skills must be unique.

Let’s start to create a form and apply a unique validation on skill name. As such, there is no unique validator available in angular and without writing too much code in the component, straightaway I will use unique validator of @rxweb/reactive-form-validators validation framework. This validation framework provides more than 50+ validators with cross-field validation.

Let’s install first @rxweb/reactive-form-validators.

npm install @rxweb/reactive-form-validators

Now, Register the ‘RxReactiveFormsModule’ in the root module.



import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import {  RxReactiveFormsModule } from "@rxweb/reactive-form-validators"
@NgModule({
  imports:      [ BrowserModule, FormsModule,ReactiveFormsModule,RxReactiveFormsModule ],
  declarations: [AppComponent],
  bootstrap:    [ AppComponent]
})
export class AppModule { }


Enter fullscreen mode Exit fullscreen mode

Now, we have to create the job application FormGroup including nested FormArray. Before creating job application FormGroup, let’s create skill FormGroup and apply the unique validator on skillName FormControl. Later, Skill FormGroup will be pushed in skills FormArray.



    getSkillFormGroup(){
      return this.formBuilder.group({
        skillName:['',RxwebValidators.unique()]
      })
    }


Enter fullscreen mode Exit fullscreen mode

Now, let’s create main job application FormGroup and inside this FormGroup, I will call previously created method ‘getSkillFormGroup’ to pushed the FormGroup in skills FormArray.



        this.jobFormGroup = this.formBuilder.group({
            fullName:[''], 
            skills:this.formBuilder.array([
              this.getSkillFormGroup()
            ])

        });


Enter fullscreen mode Exit fullscreen mode

As the nature of the job application form user will add more than one skill. To achieve this, we have to create ‘addSkill’ method and pushed the new FormGroup of skill in Skills FormArray.



    addSkill(){
      let skillsArray = <FormArray>this.jobFormGroup.controls.skills;
      skillsArray.push(this.getSkillFormGroup());
    }


Enter fullscreen mode Exit fullscreen mode

Let’s wrap all of the code in the one component.



import { Component,OnInit } from '@angular/core';
import { FormGroup,FormBuilder,FormArray } from "@angular/forms"
import { RxwebValidators } from '@rxweb/reactive-form-validators';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
 jobFormGroup: FormGroup

    constructor(
        private formBuilder: FormBuilder )
    { }

    ngOnInit() {
        this.jobFormGroup = this.formBuilder.group({
            fullName:[''], 
            skills:this.formBuilder.array([
              this.getSkillFormGroup()
            ])

        });
    }

    addSkill(){
      let skillsArray = <FormArray>this.jobFormGroup.controls.skills;
      skillsArray.push(this.getSkillFormGroup());
    }

    getSkillFormGroup(){
      return this.formBuilder.group({
        skillName:['',RxwebValidators.unique()]
      })
    }
}


Enter fullscreen mode Exit fullscreen mode

Binds the HTML as per angular practices.

That’s it…

Here is the image of the working example of unique validation in FormArray.

Please refer the working example on stackblitz

I hope you have enjoyed this post, if you have any questions or suggestions then please post the comment below.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay