添加/删除自定义验证器以形成角度8的数组

时间:2019-11-25 10:38:31

标签: javascript angular typescript

嗨,我正在尝试设置/取消可更改的表单数组中不同元素的自定义验证器,到目前为止,我试图做的是创建一个switch语句并遍历所有设置的输入类型因此,我可以设置验证规则,并在不符合该规则的情况下向用户发送消息。我遇到的问题是在设置表单数据之前初始化了表单。

所以我的问题是如何遍历数组并设置验证规则。如果有人可以通过使用switch语句让我知道im是否沿着正确的方向运行,但是代码放置在错误的位置,或者是否存在其他更好的方法,那么对您最有帮助

export class ReactiveComponent implements OnInit {
  public form: FormGroup;
  public fieldList: any;
  types: Array<any>;
  formData: any;
  Param: string;
  setData: any;
  formLabelNames: any;

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

  ngOnInit() {
    this.form = this.fb.group({
      name: ['', Validators.compose([Validators.required])],
      organization: ['', 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
  createForm(): FormGroup {
    return this.fb.group({
      type: ['', Validators.compose([Validators.required])],
      name: ['', Validators.compose([Validators.required])],
      value: ['', this.validators()]
    });
  }

  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;
  }
  getContactsFormGroup(index): FormGroup {
    const formGroup = this.fieldList.controls[index] as FormGroup;
    return formGroup;
  }
  setForm(data) {
    const d = data.results;
    this.setData = d;
    this.formLabelNames = d[0].fields;
    this.form.patchValue({
      name: [d[0].form_name],
      organization: [d[0].org],
    });
    this.form.setControl('inputs', this.setExistingFields(d[0].fields));
  }
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;
}
/* This is where I have tried to create a switch statement but I get a undefined error because the setform function is being called after this one */
validators() {
   this.formLabelNames.type.forEach((field: any) => {
     switch (field.type) {
       case 'email':
     }
   });
}
submit() {
  if (this.form.valid) {
  const formId = this.Param;
  const local = this.auth.decodePayload();
  const userId = local.sub;
  this.router.navigateByUrl('/dashboard');
  this.api.sendForm(this.form.value, formId, userId).subscribe();
  this.form.reset();
  } else {
    this.notifiy.showFailure('Form is not valid', 'Error');
  }
 }
}

1 个答案:

答案 0 :(得分:0)

据我判断,您有几个问题:

  1. 您没有在formGroup内部正确初始化formControls和formArray。它应该看起来像这样:

    this.form = this.fb.group({
      name: new FormControl( "", {validators: [Validators.required]}),
      organization: new FormControl( "", {validators: [Validators.required]}),
      inputs: this.fb.array([new FormControl(), new FormControl()]),
    });

此外:当仅由一个formGroup组成的formArray时,使用它有什么意义?

  1. 当然,您可以为任何abstractControl设置验证器,无论是formControl还是formGroup。对于数组,它看起来像这样:

    this.formArray.controls.map((ctrl) => {
      ctrl.setValidators([Validators.required, Validators.email]);
    });

  1. 将方法放在组件类中的哪个位置都没有关系。虽然何时调用该方法肯定很重要!