Angular reactive form validation with dynamically named controls

Asked
Active3 hr before
Viewed126 times

5 Answers

nameddynamicallyreactivecontrolsvalidationangular
90%

With the above method, instead of writing this in our code to get a contact form group controls value,,After installing bootstrap, import it to your angular project inside angular

Example_snippet/controller/utility/_named.js/ $ ng new angular-dynamic-form-. . .
$ ng new angular - dynamic - form - fields - reactive - forms
load more v
88%

Develop a component to create form controls dynamically,,The form you create uses input validation and styling to improve the user experience

Example_snippet/controller/utility/_named.js/ content_copy . . .
      content_copy

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

      import {
         AppComponent
      } from './app.component';
      import {
         DynamicFormComponent
      } from './dynamic-form.component';
      import {
         DynamicFormQuestionComponent
      } from './dynamic-form-question.component';

      @NgModule({
         imports: [BrowserModule, ReactiveFormsModule],
         declarations: [AppComponent, DynamicFormComponent, DynamicFormQuestionComponent],
         bootstrap: [AppComponent]
      })
      export class AppModule {
         constructor() {}
      }
load more v
72%

Here, we discuss clean approach of dynamic validation on dynamic reactive forms,,Setting up the validators on the fly while working on dynamic forms is a little bit clumsy work, because writing too much code to handle this kind of things by calling the setValidators and clearValidators method in Angular

Example_snippet/controller/utility/_dynamically.js/ setValidators. . .
setValidators
load more v
65%

The dynamic form FormGroup contains two form controls:, Angular 10 - Reactive Forms Validation Example , Angular 10 - Template-Driven Form Validation Example ,tickets is an Angular FormArray used to hold an array of form groups (FormGroup) for storing ticket holder details, Each ticket form group contains two child form controls, one for the name and one for the email of the ticket holder

Example_snippet/controller/utility/_dynamically.js/ import { Component, OnInit } f. . .
import {
   Component,
   OnInit
} from '@angular/core';
import {
   FormBuilder,
   FormGroup,
   FormArray,
   Validators
} from '@angular/forms';

@Component({
   selector: 'app',
   templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
   dynamicForm: FormGroup;
   submitted = false;

   constructor(private formBuilder: FormBuilder) {}

   ngOnInit() {
      this.dynamicForm = this.formBuilder.group({
         numberOfTickets: ['', Validators.required],
         tickets: new FormArray([])
      });
   }

   // convenience getters for easy access to form fields
   get f() {
      return this.dynamicForm.controls;
   }
   get t() {
      return this.f.tickets as FormArray;
   }
   get ticketFormGroups() {
      return this.t.controls as FormGroup[];
   }

   onChangeTickets(e) {
      const numberOfTickets = e.target.value || 0;
      if (this.t.length < numberOfTickets) {
         for (let i = this.t.length; i < numberOfTickets; i++) {
            this.t.push(this.formBuilder.group({
               name: ['', Validators.required],
               email: ['', [Validators.required, Validators.email]]
            }));
         }
      } else {
         for (let i = this.t.length; i >= numberOfTickets; i--) {
            this.t.removeAt(i);
         }
      }
   }

   onSubmit() {
      this.submitted = true;

      // stop here if form is invalid
      if (this.dynamicForm.invalid) {
         return;
      }

      // display form values on success
      alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.dynamicForm.value, null, 4));
   }

   onReset() {
      // reset whole form back to initial state
      this.submitted = false;
      this.dynamicForm.reset();
      this.t.clear();
   }

   onClear() {
      // clear errors and reset ticket fields
      this.submitted = false;
      this.t.reset();
   }
}
load more v
75%

In my Angular 7 app using reactive forms I'm creating input elements based on an *ngFor loop, so I end up with an input dynamically named:, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,PS: I've made a few updates to the StackBlitz that you've shared including things that Angular Style Guide recommends along with the actual solution, Hope that helps

Example_snippet/controller/utility/_dynamically.js/ import { Component } from '@an. . .
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';

export interface Data {
  abbrev: string;
  max: number;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  workForm: FormGroup;
  workLeft: any[];

  constructor(private fb: FormBuilder) {}

  ngOnInit () {

    this.workForm = this.fb.group({
      points: this.fb.array([])
    });

    this.fillFormArray();
  }

  private fakeWebserviceCall(): Data[] {
    return [
      { abbrev: 'foo', max: 12 },
      { abbrev: 'bar', max: 10 }
    ];
  }

  private fillFormArray() {
    this.workLeft = this.fakeWebserviceCall();
    const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
    formControlsArray.forEach(control => this.points.push(control));
    console.log(this.workForm.value);
  }

  get points(): FormArray {
    return <FormArray>this.workForm.get('points');
  }

  pointAt(index) {
    return (<FormArray>this.workForm.get('points')).at(index);
  }

}
load more v