使用fromGroup生成的角动态formControlName

时间:2019-03-06 15:47:30

标签: json angular html5 dynamic

我创建了一个由JSON数组组成的表单,据此,我正在生成Validation,formControlName并通过formGroup生成输出。

this.ELEMENT_DATA_UPDATE = [
  {
        first_name : 'abc',
        last_name : 'xyz',
        phone : 8888888888
  }
];

在这里,我使用的是Angular材质,因此将该键值对转换为另一个包含

的数组
{"key" : "first_name" , "value" : "abc" , "name" : "First name :"}

这是输入JSON数组固定的情况。但是我的项目包括大规模的数据处理,其中输入JSON数组的内容将改变很多次。生成UI模块没有问题,但是当我尝试将Validation和Forms模块应用于此动态生成的内容时,整个流程就会崩溃,

这是我的代码

var jsonArray : any = [{}];

export class UpdateContactFieldDialog {

  matcher = new MyErrorStateMatcher();

  updateForm: FormGroup;

  formString : string = null;
  ELEMENT_DATA_UPDATE : any[] = [];
  keyArray : any[] = [];

  myJobFunctionControl = new FormControl();
    optionsJobFunction: string[] = ['Operations', 'Production', 'Manufacturing'];

  myTitleControl = new FormControl();
    optionsTitle: string[] = ['HR', 'Developer', 'Tester', 'MD', 'CEO', 'Director'];



  constructor(private formBuilder: FormBuilder,private dialogRef: MatDialogRef<AddContactFieldDialog> ) { 

  }

  ngOnInit() {


    //dumy randomly geneated fields
    this.ELEMENT_DATA_UPDATE = [
      {
            first_name : 'abc',
            last_name : 'xyz',
            job_function : 'Production',
            title : 'Developer',
            email : 'abc@abx.com',
            phone : 7945612304
      }
    ];

    for (let obj of this.ELEMENT_DATA_UPDATE) {

        console.log("object length:", this.ELEMENT_DATA_UPDATE.length);
        for (let key in obj) {
            this.keyArray.push({'key' : key , 'value' : obj[key] , 'name': (key.charAt(0).toUpperCase() + key.substr(1).toLowerCase()).replace(/_/g, ' ')});
        }
        break;
    }
    console.log(this.keyArray);
    console.log(this.ELEMENT_DATA_UPDATE[0]);


      for(let formModule of this.keyArray){
       var keyData = formModule.key;
       
        if(this.formString != null && keyData == 'email' || keyData.includes('mail')){
            this.formString = this.formString +''+keyData+':[this.ELEMENT_DATA_UPDATE[0].'+keyData +',[Validators.required,Validators.email]], ';  
        }
        else
          if(this.formString != null && keyData == 'phone' || keyData.includes('number')  || keyData.includes('no') || keyData.includes('num')  ){
            this.formString = this.formString +''+keyData+':[this.ELEMENT_DATA_UPDATE[0].'+keyData +',[Validators.required,Validators.minLength(10),Validators.maxLength(10),Validators.pattern("[0-9]*")]], ';  
        }
        else
        if(this.formString == null && keyData != 'email' && keyData != 'phone'){
          this.formString = ''+keyData+':[this.ELEMENT_DATA_UPDATE[0].'+keyData +',Validators.required], '; 
        }
        else{
            this.formString = this.formString + ''+keyData+':[this.ELEMENT_DATA_UPDATE[0].'+keyData +',Validators.required], ';  
        }

      }
      console.log(this.formString);

        jsonArray = (this.formString);
    this.updateForm = this.formBuilder.group(jsonArray);
         
  }

  // convenience getter for easy access to form fields
  get f() { return this.updateForm.controls; }

  submitContact() {
      this.submitted = true;

      // stop here if form is invalid
      if (this.updateForm.valid) {
        // alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.updateForm.value))
        console.log(this.updateForm.value);
        this.dialogRef.close();
      }
      else{
        return;      
      }
  }

}

我的代码正在生成以下字符串形式的代码

first_name: ['', Validators.required],
last_name: ['', Validators.required],
job_function: ['', [Validators.required]],
title: ['', [Validators.required]],
email: ['', [Validators.required, Validators.email]],
phone : ['',[Validators.required, Validators.minLength(10), Validators.maxLength(10),  Validators.pattern('[0-9 ]*')]]

我希望在formGroup内部使用它,以便我可以动态生成formControls,为它们分配验证和值。

updateForm = this.formBuilder.group(jsonArray);

1 个答案:

答案 0 :(得分:1)

补充我的评论,注意:您需要添加验证器(我在您的代码中看不到它们)

this.updateForm=new FormGroup({}) //<--create the formGroup
for(let formModule of this.keyArray){
    this.updateForm.addcontrol(formModule.key,new FormControl(formModule.Value))
}

此外,如果我们在keyArray中的对象就像

{ "key" : "key_name" , 
   "value" : "value" , 
   "name" : "Key name" ,
   validators:[Validators.required, Validators.email]
}

我们可以改善循环

for(let formModule of this.keyArray){
    this.updateForm.addcontrol(formModule.key,
          new FormControl(formModule.Value,formModule.validators))
}

好吧,如果很难像我们展示的那样使我们的对象成为一项服务,但是我们的服务有可能像以下那样为我们服务:

{ "key" : "key_name" , 
   "value" : "value" , 
   "name" : "Key name" ,
   validators:[{type:"required"},{type="min",args:3}]
}

在进行循环之前,我们可以使用

this.keyArray.forEach(x=>
{
   if (x.validators)
   {
      conts validators=[];
      validators.forEach(v=>{
          switch (v.type)
          {
               case "required":
                   validators.push(Validators.required);
                   break;
               case "min":
                   validators.push(Validators.min(v.arg);
                   break;
               ...
          }
      })
      x.validators=validators;
   }
}

关于要显示错误,我们必须考虑到表单中的控件是

updateForm.get(keyArray.key)

例如,

<div class="col-lg-6" *ngFor="let keyArray of keyArray"> 
   <mat-form-field> 
        <input type="text" [formControlName]="keyArray.key" matInput 
            [placeholder]="keyArray.name" 
            [ngClass]="{ 'is-invalid': submitted && updateForm.get(keyArray.key).errors }" 
            autocomplete="off" />
         <mat-error *ngIf="submitted && updateForm.get(keyArray.key).hasError('required')">
             {{keyArray.name}} is <strong>required</strong> 
         </mat-error>
     </mat-form-field>
</div>