skip to Main Content

I have an object that should build a form

const textBox = {
  fontColor: 'red',
  fontSize: '20',
  placeholder: 'name',
  name: 'input name',
  label: 'mohamed',
  validation: {
    required: true
  }
};

I created a simple dynamic form but I need to set the validators with each form control

ngOnInit(): void {
  const inputDataObj = {} as any;
  for (const prop of Object.keys(this.InputObj)) {
    debugger;
    if (prop !== 'validation') {
      inputDataObj[prop] = new FormControl(this.InputObj[prop]);
      this.inputProps.push(prop);
    }
  }
  this.form = new FormGroup(inputDataObj);
}

now I need to set validation to any form control, the validation is an optional property,
some objects may not have any validations

2

Answers


  1. I take it that you’d like to add validation only when the required property in your validation object is set to true.

    If so, you want to first create the FormControl and then use the addValidators method to dynamically add validation:

    import { Component } from '@angular/core';
    import { FormControl, FormGroup, Validators } from '@angular/forms';
    
    const textBoxes = [
      {
        fontColor: 'red',
        fontSize: '20',
        placeholder: 'name',
        name: 'input name',
        label: 'mohamed',
        validation: {
          required: true,
        },
      },
    ];
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      public form = new FormGroup({});
      ngOnInit(): void {
        for (const textbox of textBoxes) {
          const control = new FormControl(textbox.placeholder);
          if(textbox.validation.required){
            control.addValidators(Validators.required);
          }
          this.form.addControl(textbox.name, control);
        }
      }
    }
    

    Stacblitz

    Login or Signup to reply.
  2. // Your component

      ngOnInit() {
    
    const textBoxes = [
      {
        fontColor: 'red',
        fontSize: '20',
        placeholder: 'name',
        name: 'input name',
        label: 'mohamed',
        validation: [
          required: true,
          min: 5,
        ],
      },
    ];
    
        this.createForm(textBoxes);
      }    
    
      createForm(controls: YourModel[]) {
        this.formGroup = this.service.toFormGroup(controls);
      }
    

    // service (is better if you split your functionality in a service)

      validatorsMap = {
        required: () => Validators.required,
        min: (num: number) => Validators.min(num),
        ... etc: etc(),
        ... etc: etc(),
      };
    
    
      toFormGroup(inputs: YourModel[]): FormGroup {
    
          const group: any = {};
    
          inputs.forEach(input => {
    
              const validations: any[] = this.getValidators(input);
    
              group[input.name] = new FormControl(
                '', // initial value
                validations// here are that you want!
              );
            });
    
          return new FormGroup(group);
    
      }
    
      getValidators(input: ControlModel) {
    
        return input.validation
          .map(validation => {
            return fn = this.validatorsMap[validation.name];
          });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search