N Level Form Array with Dynamically Validation in Angular
Tags: angular, tutorial, typescript, javascript
Published: 2022-04-08 06:12:15

<!-- wp:paragraph -->
<p>In this tutorial article, we will cover the form with multiple sub-form (nested form) along with each sub-form have custom validation in Angular.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-problem-statement">Problem Statement</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Create a form with N number of sub-forms, each with N number of listed items, and submit the entire form at once, with specific validation in each form/form array.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Use Case</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><strong>Let’s say</strong>, you had to create a gateway for Family Information that included basic information as well as various Address Details, Income Details, Expense Details, Education Details, Sickness Details, and so on. Furthermore, each family has several family members, and each family member has various education, spending, and income statistics. All forms contain N details and distinct fields, as well as dynamic validation when data is entered.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":15034,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/Use-case-image-1024x618.png" alt="Use case image" class="wp-image-15034"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":4} -->
<h4>Prerequisites</h4>
<!-- /wp:heading -->

<!-- wp:list {"ordered":true} -->
<ol><li>Prior knowledge of <a href="https://www.tutorialspoint.com/typescript/index.htm" target="_blank" rel="noreferrer noopener">TypeScript</a></li><li>Prior knowledge of <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps" target="_blank" rel="noreferrer noopener">JavaScript</a></li><li>Visual studio code</li><li>A <a href="https://nodejs.org/en/download/releases/" target="_blank" rel="noreferrer noopener">development machine</a> with Node 10+ &amp; NPM 5.5.1+ installed</li></ol>
<!-- /wp:list -->

<!-- wp:heading -->
<h2 id="h-create-n-level-formarray-with-reactive-form-validation-in-angular-step-by-step-tutorial">Create N Level FormArray with Reactive Form Validation in Angular: Step by Step Tutorial</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Step 1: Create New Angular Project</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Import the ReactiveFormsModule and FormsModule in app.module.ts Also, add it to the imports array of NgModule of the AppModule</li></ul>
<!-- /wp:list -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { FormsModule, ReactiveFormsModule } from '@angular/forms';</code></pre>
<!-- /wp:code -->

<!-- wp:image {"align":"center","id":15033,"sizeSlug":"full","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-full"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/Forms-Module-image.png" alt="Forms Module" class="wp-image-15033"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Step 2: App.component.ts</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>Now</strong>, Create a simple form first in app.component.ts and import the below the line and add a new form something like this with validation</li></ul>
<!-- /wp:list -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { FormArray,FormBuilder,FormControl,FormGroup,Validators } from '@angular/forms';</code></pre>
<!-- /wp:code -->

<!-- wp:image {"align":"center","id":15032,"sizeSlug":"full","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-full"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/Form-Array-image.png" alt="Form Array image" class="wp-image-15032"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Step 3: App.component.html</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>App.component.html should look like this with a validation message message</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":15031,"sizeSlug":"full","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-full"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/App-component-html-code-image.png" alt="App component html code" class="wp-image-15031"/></figure></div>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li><strong>Run the command</strong>: npm start and open the browser localhost:4200/ - it will look like this and validation should fire on the touch that textbox or press submit button</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":15030,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/run-the-command-image-1024x474.png" alt="run the command image" class="wp-image-15030"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Step 4: Form-Array</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Let’s move toward the FormArray, and try to add the first array assume we have to add the “Education Details” list.</li><li>Add new member in form declaration part like this</li></ul>
<!-- /wp:list -->

<!-- wp:code -->
<pre class="wp-block-code"><code>educationdata: 
this.fb.array(&#91;])</code></pre>
<!-- /wp:code -->

<!-- wp:image {"align":"center","id":15029,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/form-array-code-image-1024x549.png" alt="form array code" class="wp-image-15029"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Step 5: Declare FormArray Function Like This</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>educationdata(): FormArray {
    return this.myForm.get('educationdata') as FormArray;
  }</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Step 6: Create A New Form Like This</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>neweducationdata(): FormGroup {
    return this.fb.group({
      schoolName: new FormControl(''),
      degree: new FormControl(''),
      fieldofstudy: new FormControl(''),
      startDt: new FormControl(''),
      endDt: new FormControl(''),
      grade: new FormControl(''),
      notes: new FormControl(''),
      attachmenturl: new FormControl(''),
    });
  }</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Step 7: Add New Array Function</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>educationcon(index) {
    this.educationList = this.myForm.get('educationdata') as FormArray;
    const formGroup = this.educationList.controls&#91;index] as FormGroup;
    return formGroup;
  }</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Step 8: Remove New Array Function</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>removeeducationdata(i: number) {
    this.educationdata().removeAt(i);
  }</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Step 9: Add Validation Management Like This</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>educationcon(index) {
 this.educationList = this.myForm.get('educationdata') as FormArray; const formGroup = this.educationList.controls&#91;index] as FormGroup;
    return formGroup;
}</code></pre>
<!-- /wp:code -->

<!-- wp:list -->
<ul><li>Ts code should look like this</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":15028,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/ts-code-image-1024x632.png" alt="ts code" class="wp-image-15028"/></figure></div>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li>The HTML code should be like this</li></ul>
<!-- /wp:list -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;table
   class="table table-bordered"
   formArrayName="educationdata"
   &gt;
   &lt;tr&gt;
      &lt;th colspan="7"&gt;Add More Data:&lt;/th&gt;
      &lt;th width="150px"&gt;
         &lt;button
            type="button"
            (click)="addeducationdata()"
            class="btn btn-primary"
            &gt;
         Add More
         &lt;/button&gt;
      &lt;/th&gt;
   &lt;/tr&gt;
   &lt;tr
   *ngFor="let f of educationdata().controls; let i = index"
   &#91;formGroupName]="i"
   &gt;
   &lt;td&gt;
      School/College Name :
      &lt;input
         type="text"
         formControlName="schoolName"
         class="form-control"
         /&gt;
   &lt;/td&gt;
   &lt;td&gt;
      Degree:
      &lt;select formControlName="degree" class="form-control"&gt;
         &lt;option value=""&gt;Select Degree&lt;/option&gt;
         &lt;option value="SCHOOL"&gt;School Degree&lt;/option&gt;
         &lt;option value="COLLEGE"&gt;Some College&lt;/option&gt;
         &lt;option value="BACHELOR"&gt;Bachelor Degree&lt;/option&gt;
         &lt;option value="MASTER"&gt;Master Degree&lt;/option&gt;
         &lt;option value="PHD"&gt;PhD Degree&lt;/option&gt;
      &lt;/select&gt;
   &lt;/td&gt;
   &lt;td&gt;
      Field Of Study:
      &lt;input
         class="form-control"
         type="text"
         formControlName="fieldofstudy"
         /&gt;
   &lt;/td&gt;
   &lt;td&gt;
      Start Date:
      &lt;input
         class="form-control"
         type="date"
         formControlName="startDt"
         /&gt;
   &lt;/td&gt;
   &lt;td&gt;
      End Date:
      &lt;input
         class="form-control"
         type="date"
         formControlName="endDt"
         /&gt;
   &lt;/td&gt;
   &lt;td&gt;
      Grade:
      &lt;input
         class="form-control"
         type="text"
         formControlName="grade"
         /&gt;
   &lt;/td&gt;
   &lt;td&gt;
      Notes:
      &lt;textarea
         class="form-control"
         formControlName="notes"
         &gt;&lt;/textarea&gt;
   &lt;/td&gt;
   &lt;td&gt;
      &lt;button
         (click)="removeeducationdata(i)"
         class="btn btn-danger"
         &gt;
      Remove
      &lt;/button&gt;
   &lt;/td&gt;
   &lt;/tr&gt;
&lt;/table&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:list -->
<ul><li>When you run the project the UI will look like this, I have used a tab (bootstrap tab), you can add N number of an array and remove any specific array.</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":15027,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/project-ui-image-1024x469.png" alt="project ui" class="wp-image-15027"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Now Let’s Add Validation In The Nested Array</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Step 1: Add A Display Message Like This</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>validation_edumessage = {
    schoolName: &#91;{ type: 'required', message: 'School Name is required' }],
    degree: &#91;{ type: 'required', message: 'Degree is required' }],
    startDt: &#91;{ type: 'required', message: 'Start Date is required' }]};</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Step 2: Add Validation In Education From The Group</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>neweducationdata(): FormGroup {
    return this.fb.group({
      schoolName: new FormControl('', &#91;Validators.required]),
      degree: new FormControl('', &#91;Validators.required]),
      fieldofstudy: new FormControl(''),
      startDt: new FormControl('', &#91;Validators.required]),
      endDt: new FormControl(''),
      grade: new FormControl(''),
      notes: new FormControl('')}); }</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Step 3: Add Validation In Form Html Like This</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;input type="text" formControlName="schoolName"
   class="form-control" 
   &#91;ngClass]="{'is-invalid':
    educationcon(i).controls&#91;'schoolName'].errors &amp;&amp;
    (educationcon(i).controls&#91;'schoolName'].dirty ||                        educationcon(i).controls&#91;'schoolName'].touched)}"/&gt;

  &lt;div *ngFor="let validation of validation_edumessage.schoolName"
   class="invalid-feedback"&gt;
   &lt;div  *ngIf="educationcon(i).controls&#91;'schoolName'].hasError(validation.type) 
&amp;&amp; (educationcon(i).controls&#91;'schoolName'].dirty || educationcon(i).controls&#91;'schoolName'].touched)"&gt;
 &lt;/div&gt; &lt;/div&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:list -->
<ul><li>UI should look like this:</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":15026,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/ui-output-image-1024x169.png" alt="ui output" class="wp-image-15026"/></figure></div>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li>When you submit a form we will get all data like this (capture from console)</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":15025,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://www.samarpaninfotech.com/wp-content/uploads/2022/04/code-image-from-console-1024x344.png" alt="code from console" class="wp-image-15025"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Over To You!</h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"style":{"color":{"background":"#e1e4e5"}}} -->
<p class="has-background" style="background-color:#e1e4e5">Looking for a <em>Sample Source Code</em>? Here you go: <a href="https://github.com/sandipmalaviya07/nested-form-array-with-validation">GITHUB</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That’s it for now. Today you have learned how to create N Level FormArray With Reactive Form Validation using Angular. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>At last, If you’re dealing with large-scale applications or enterprise software, it is beneficial to take experts’ help. If you’re looking for an expert helping hand, contact Samarpan Infotech and <a href="https://www.samarpaninfotech.com/hire-angularjs-developers/">hire Angular developers</a> with having minimum of 5+ years of experience working on enterprise software.</p>
<!-- /wp:paragraph -->