How to edit nested reactive form with validation?

Asked
Active3 hr before
Viewed126 times

5 Answers

validationnestedreactive
90%

Learn how to use Angular's FormArray class to dynamically add and remove FormGroups and FormControls in reactive forms,,Now we have a form that dynamically adds and removes FormGroups to allow the user to create as many users as they would like

Example_snippet/controller/utility/_validation.js/ abstract class AbstractControl. . .
abstract class AbstractControl {
   constructor(validator: ValidatorFn, asyncValidator: AsyncValidatorFn)
   value: any
   validator: ValidatorFn | null
   asyncValidator: AsyncValidatorFn | null
   parent: FormGroup | FormArray
   status: string
   valid: boolean
   invalid: boolean
   pending: boolean
   disabled: boolean
   enabled: boolean
   errors: ValidationErrors | null
   pristine: boolean
   dirty: boolean
   touched: boolean
   untouched: boolean
   valueChanges: Observable
   statusChanges: Observable
   updateOn: FormHooks
   root: AbstractControl
   setValidators(newValidator: ValidatorFn | ValidatorFn[]): void
   setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[]): void
   clearValidators(): void
   clearAsyncValidators(): void
   markAsTouched(opts: {
      onlySelf ? : boolean;
   } = {}): void
   markAsUntouched(opts: {
      onlySelf ? : boolean;
   } = {}): void
   markAsDirty(opts: {
      onlySelf ? : boolean;
   } = {}): void
   markAsPristine(opts: {
      onlySelf ? : boolean;
   } = {}): void
   markAsPending(opts: {
      onlySelf ? : boolean;emitEvent ? : boolean;
   } = {}): void
   disable(opts: {
      onlySelf ? : boolean;emitEvent ? : boolean;
   } = {}): void
   enable(opts: {
      onlySelf ? : boolean;emitEvent ? : boolean;
   } = {}): void
   setParent(parent: FormGroup | FormArray): void
   abstract setValue(value: any, options ? : Object): void
   abstract patchValue(value: any, options ? : Object): void
   abstract reset(value ? : any, options ? : Object): void
   updateValueAndValidity(opts: {
      onlySelf ? : boolean;emitEvent ? : boolean;
   } = {}): void
   setErrors(errors: ValidationErrors, opts: {
      emitEvent ? : boolean;
   } = {}): void
   get(path: string | (string | number)[]): AbstractControl | null
   getError(errorCode: string, path ? : string | (string | number)[]): any
   hasError(errorCode: string, path ? : string | (string | number)[]): boolean
}
load more v
88%

Reactive forms provide a model-driven approach to handling form inputs whose values change over time, This guide shows you how to create and update a basic form control, progress to using multiple controls in a group, validate form values, and create dynamic forms where you can add or remove controls at run time

Example_snippet/controller/utility/_validation.js/ content_copy . . .
      content_copy

      import {
         ReactiveFormsModule
      } from '@angular/forms';

      @NgModule({
         imports: [
            // other imports ...
            ReactiveFormsModule
         ],
      })
      export class AppModule {}
load more v
72%

If you are new to Reactive Forms, please refer to Full Angular Reactive Forms & Form Validation Tutorial,,To work with Reactive Forms in Angular, please import ReactiveFormsModule service in app

Example_snippet/controller/utility/_validation.js/ import { ReactiveFormsModule }. . .
import {
   ReactiveFormsModule
} from '@angular/forms';

@NgModule({
   imports: [
      ReactiveFormsModule
   ],
})

export class AppModule {}
Step 2 continued with <!-- Form starts --> <form [fo. . .
<!-- Form starts -->
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
   <button type="submit" class="btn btn-danger btn-lg btn-block">Submit Form</button>
</form><!-- Form ends -->
Step 3 continued with import { Component } from '@an. . .
import {
   Component
} from '@angular/core';
import {
   FormBuilder,
   FormArray
} from "@angular/forms";

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {

   constructor(public fb: FormBuilder) {}

   /*############ Registration Form ############*/
   registrationForm = this.fb.group({
      addDynamicElement: this.fb.array([])
   })

   // Submit Registration Form
   onSubmit() {
      alert(JSON.stringify(this.registrationForm.value))
   }

}
load more v
65%

These are the 3 steps required to create Nested Reactive Form, Step 1: create a new application in angular using the command,,Most of the applications that are built today are just forms, there are numerous forms, and even some of those are dynamic

Example_snippet/controller/utility/_nested.js/ For example, { "name": 'abc', . . .
For example, {
   "name": 'abc',
   "addressess": [{
         "street": 'nehru nagar',
         "phone number": [{
               number1: 9845612378
            },
            {
               number2: 1589635015
            }
         ]
      },
      {
         "street": 'gandhi nagar',
         "phone number": [{
               number1: 7412563474
            },
            {
               number2: 1578963248
            }
         ]
      }
   ]
}
load more v
75%

Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , Stack Overflow Public questions & answers , Outdated Answers: accepted answer is now unpinned on Stack Overflow ,Thanks for contributing an answer to Stack Overflow!

Example_snippet/controller/utility/_nested.js/ addAddress(data:any) { /. . .
  addAddress(data: any) {
     //if received a null, create a data with the necesary properties
     data = data || {
        template: {
           from: '',
           : '',
           name: '',
           subject: '',
           ...
        },
        sequentialOrder: 0,
        ...
     }
     return this._fb.group({
        EmailType: [data.template.from, Validators.required],
        name: [data.template.name, Validators.required],
        subject: [data.template.subject, Validators.required],
        'from': [data.template.from, [Validators.required, ValidationService.emailValidator]],
        'body': [data.template.body, [Validators.required]],
        'active': [data.template.active],
        'confidential': [data.template.confidential],
        'numberOfDaysToWait': [data.numberOfDaysToWait, Validators.required],
        'sequentialOrder': [data.sequentialOrder, Validators.required]
     });
  }
load more v