繁体   English   中英

具有动态字段的 Angular Reactive Form

[英]Angular Reactive Form with dynamic fields

我目前正在与 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>

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

任何人都可以帮我解决这个问题吗? 也许有更好的方法来做到这一点。

好吧,我觉得直接使用formControlformGroup的构造函数更舒服

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>

堆栈闪电战

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM