具有动态字段的角反应形式

时间:2020-01-27 16:52:27

标签: javascript angular forms formarray formgroups

我目前正在与Angular表单数组作战。

我有一个表单,可以动态添加字段。

我已经创建了表单对象:

this.otherDataForm = this.fb.group({
});

我添加这样的动态字段:

addField(field: CustomFormField): void {
    this.otherDataForm.addControl(id_campo, new FormControl('', Validators.required));
}

我遍历这些字段:

<form *ngIf="selectedProfile" [formGroup]="otherDataForm">
      <div class="mb-3" *ngFor="let field of fields; let i = index">
           <label>{{field.descripcion}}</label>
           <input class="form-control" [formControlName]="field.id_campo" type="number">
      </div>
</form>

但是我似乎无法控制每个字段的错误以显示验证消息(如果需要该字段)。

有人可以帮助我吗? 也许有更好的方法可以做到这一点。

1 个答案:

答案 0 :(得分:4)

好吧,我觉得formControl和formGroup的构造函数在使用上更方便

fields=[{id:'one',label'one',value:1},{id:'two',label'two',value:2}]
form=new FormGroup({})
ngOnInit()
{
   this.fields.forEach(x=>{
    this.form.addControl(x.id,new FormControl(x.value,Validators.Required))
   })
}

<form [formGroup]="form">
    <div *ngFor="let field of fields">
        <input [formControlName]="field.id">
        <div class="error" *ngIf="form.get(field.id).touched &&
            form.get(field.id).invalid">Required</div>
    </div>
</form>
{{form?.value|json}}

但是您可以直接在输入中使用[formControl]

<form [formGroup]="form">
    <div *ngFor="let field of fields">
    <label>{{field.label}}</label>
        <input [formControl]="form.get(field.id)">
        <div class="error" *ngIf="form.get(field.id).touched && 
             form.get(field.id).invalid">Required</div>
    </div>
</form>

甚至,您也可以遍历form.controls | keyvalue

<form [formGroup]="form">
    <div *ngFor="let control of form.controls |keyvalue;let i=index">
    <label>{{fields[i].label}}</label>
    <input [formControl]="control.value">
        <div class="error" *ngIf="control.value.touched && 
               control.value.invalid">Required</div>
    </div>
</form>

请参阅stackblitz