Home > Software engineering >  Create dynamic form field inside form with dynamic validation in Angular
Create dynamic form field inside form with dynamic validation in Angular

Time:12-27

I have this data

"data": [
            {
                "sno": 1,
                "name": "name",
                "nameLabel": "Name",
                "isRequired": 1,
                "maxLen": 50,
                "order": 1,

            },
            {
                "sno": 2,
                "name": "desc",
                "nameLabel": "Description",
                "isRequired": 1,
                "maxLen": 50,
                "order": 2,
            },
            ..
            ..

I have to create these fields dynamically in form and use dynamic validation. If isRequired is 1 then that field is required, maxLen also we have to validate.

Any solution Thanks

CodePudding user response:

follow the below way :)

for (const field of this.data) {
      let validators = [];
      if (field.isRequired) {
        validators.push(Validators.required);
      }
      if (field.maxLen) {
        validators.push(Validators.maxLength(field.maxLen));
      }
      this.form.addControl(field.name, this.fb.control('', validators));
    }

CodePudding user response:

Your HTML should be like

<form *ngIf="Data != null && Data.length > 0" [formGroup]="rForm">
  <div >
    <div  *ngFor="let control of rForm.value | keyvalue">
        <label for="">Email</label>
        <input type="text"  placeholder="Email" [formControlName]="control.key">
        <span *ngIf="form.get(control.key).errors?.required">Field is required</span>
    </div>
  </div>
</form>

Your typescript should be like

for (const field of this.data) {
  let validators = [];
  if (field.isRequired) {
    validators.push(Validators.required);
  }

  if (field.maxLen) {
    validators.push(Validators.maxLength(field.maxLen));
  }

  this.form.addControl(field.name, this.fb.control('', validators));
}

Thanks!

  • Related