补充我的意见,注意:您需要添加验证器(我在您的代码中看不到它们)
this.updateForm=new FormGroup({}) //<--create the formGroup
for(let formModule of this.keyArray){
this.updateForm.addcontrol(formModule.key,new FormControl(formModule.Value))
}
{ "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>