动态表单中表单控件的动态验证-Angular 7

时间:2019-12-10 11:51:19

标签: angular angular7 angular-reactive-forms

我正在创建带有一组FormControls的FormGroup,其中包含一组这样的对象:

import { Component, OnInit } from '@angular/core'
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class App implements OnInit {
 formData : Array<{type:string , formFieldName:string , required?: boolean } = [
  {
    type : 'text',
    formFieldName:'field1',
    required : true
  },
  {
    type : 'text',
    formFieldName:'field2',
    required : true
  },{
    type : 'text',
    formFieldName:'field3',
  },
 ];
 ngOnInit() {
    const formFields = this.formData.reduce(
      (formObj, fieldMetaData) => Object.assign(formObj, {
        [fieldMetaData.formFieldName]: new FormControl('' , Validators.required )}), {});
     this.form = new FormGroup(formFields);
 }
}

我必须基于JSON对象设置Validators.required。像这样:

[fieldMetaData.formFieldName]: new FormControl('' , fieldMetaData.required ? Validators.required : null )}), {});

我该如何实现?

1 个答案:

答案 0 :(得分:1)

尝试一下。

new FormControl('' , fieldMetaData.required ? [Validators.required] : [])