使用响应式表单的Angular 7动态表单验证

时间:2019-11-12 14:39:56

标签: javascript angular typescript

我目前正在开发一个动态表单生成器,它具有管理员方和用户方,在管理员方可以设置输入名称并键入,例如:名字和文本框,您可以添加或删除字段和您可以选择一定数量的类型,完成后,管理员会将表单保存到数据库中。在用户前端,将from从数据库中提取出来,并使用patchValue将from设置为我对用户对表单问题的输入所遇到的问题。我试图弄清楚如何首先设置用户用来回答问题的输入的类型和占位符。

以及将验证规则动态地应用于每个输入,因此,例如,用户想要使用我想要的名字和姓氏填写其名字,姓氏,年龄和简历的表单和一个正则表达式只允许某些字符,对于这个年龄,我想要一个最小和最大数字以及简历。当用户提交表单时,我只想发送输入的名称和值,而不是整个表单。

但是请记住,这些表格是完全动态的,因此我需要根据设置的输入类型来验证用户的输入

/*Typescript Code*/
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FormService} from '../form.service';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-reactive',
  templateUrl: './reactive.component.html',
  styleUrls: ['./reactive.component.scss']
})
export class ReactiveComponent implements OnInit {
  public form: FormGroup;
  public fieldList: any;
  types: Array<any>;
  formData: any;
  Param: string;

  get contactFormGroup() {
    return this.form.get('inputs') as FormArray;
  }
  constructor(
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private api: FormService) { }

  ngOnInit() {
  /*First I initlize the form*/
    this.form = this.fb.group({
      name: [null, Validators.compose([Validators.required])],
      organization: [null, Validators.compose([Validators.required])],
      inputs: this.fb.array([this.createForm()])
    });
    this.route.paramMap.subscribe(params => {
      this.Param = params.get('id');
      this.getForm(this.Param);
    });
    // set fieldslist to this field
    this.fieldList = this.form.get('inputs') as FormArray;
  }

  // formgroup
  /*The I initilize the form array of inputs*/
  createForm(): FormGroup {
    return this.fb.group({
      type: [null, Validators.compose([Validators.required])],/*These come from the DB*/
      name: [null, Validators.compose([Validators.required])],/*These come from the DB*/
      value: [null, Validators.compose([Validators.required])] /*This gets filled in by the user*/
    });
  }
  /*The I use my API service to call the DB using the form Id*/
  getForm(id) {
    this.api.getForm(id).subscribe(
      (data: any) => this.setForm(data)
    );
  }
getFieldsFormGroup(index): FormGroup {
    const formGroup = this.fieldList.controls[index] as FormGroup;
    return formGroup;
  }
  /*Here I set my form data*/
  setForm(data) {
    const d = data.results;
    this.form.patchValue({
      name: [d[0].form_name],
      organization: [d[0].org],
    });
    this.form.setControl('inputs', this.setExistingFields(d[0].fields));
  }
  /*Here I set my inputs array data*/
setExistingFields(fields: any): FormArray {
  const formArray = new FormArray([]);
  this.fieldList = formArray;
  fields.forEach(f => {
    formArray.push(this.fb.group({
      name: f.name,
      type: f.type,
      value: f.value
    }));
  });
  return formArray;
}
submit() {
/* Here when I send my form back to the server I only want to send the inputs name and value nothing else */
  console.log(this.form.value.inputs);
 }
}
/*HTML CODE*/
<div class="container p-1">
  <div class="row">
    <div class="col-12">
      <form class="md-form" [formGroup]="form" #submittion (submit)="submit()">
        <div class="card">
          <div class="card-header">Form Name</div>
          <div class="card-body">
            <div class="row">
              <div class="form-group col-6">
                <i class="fab fa-wpforms prefix"></i>
                <input class="form-control" placeholder="Form Name" formControlName="name" type="text" readonly>

              </div>
              <div class="form-group col-6">
                <i class="far fa-building prefix"></i>
                <input class="form-control" placeholder="Organization" formControlName="organization" type="text"
                  readonly>
              </div>
            </div>
          </div>
          <div class="card-header col-12">Please fill in all fields. </div>
          <div class="card-body" formArrayName="inputs">
            <div class="row">
              <div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
                <div [formGroupName]="i" class="row z-depth-1 m-1 p-1">
                  <div class="form-group col-6">
                    <input class="form-control" formControlName="name" type="text" readonly>
                  </div>
                  <div class="form-group col-6">
                  <1-- This is the input that the user will fill in and I am not sure how to dynamically set the type or placeholder this is what I am trying to achieve -->
                    <input class="form-control" type="" placeholder=""
                      formControlName="value" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
<div class="icon-bar round">
  <button class="btn btn-success round m-1" type="submit" (click)="submit()"><i class="fas fa-save">  Save Form</i></button>
</div>

对此,任何帮助都非常有用,我已经尝试了一段时间,谢谢

0 个答案:

没有答案
相关问题