Quick Solution: Unique value validation in FormArray of Angular

Ajay Ojha
2 min readDec 19, 2018

--

Here I will discuss the approach of unique value validation on FormControl inside the FormArray.

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

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.

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.

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.

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

Binds the HTML as per angular practices.

That’s it…

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

Here is the working example of stackblitz:

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

--

--