如何在表单中设置动态字段及其值?

问题描述 投票:1回答:1
  • 我使用的是angular form Control,我有一组值要在表单中显示,有几个是静态的,几个是动态的。
  • 我有一组值要显示在一个表单中,少数是静态的,少数是动态的。
  • 我正在用formControlName和我在fb组中收到的ts文件显示静态值,如下所示。

对于已知值,我的做法如下。

Html文件

<input type = "text" formControlName="catalogItemId">

Ts文件

this.catalog Form = this.fb.group({
catalogItemId:fb.control('').
.
.
so on
})

对于动态值(未知值),我正在进行如下循环(因为我不知道什么字段会出现在这里)。

<mat-list-item *ngFor="let data of attributeMap | keyvalue">
     <mat-form-field>
         <mat-label>{{data.key}}</mat-label>
         <input matInput type="text" value = {{data.value}}
     </mat-form-field>
</mat-list-item>

现在的问题是,我如何才能在我的表单组(即this.catalog Form)中获取这些动态值。

我以前没有用过表单生成器,我通过很多文章来澄清这个疑问.希望能得到解决.先谢谢你了。

angular angular-forms form-control angular-formbuilder
1个回答
1
投票

你可以使用 addControl() 由于你可能只想在模板中循环动态控件,我建议你在表单中创建一个嵌套的表单组,将其与表单中的静态控件隔离开来。

this.catalogForm = this.fb.group({
 catalogItemId:fb.control(''),
 dynamicControls: this.fb.group({})
});
addDynamicValues() {
 for (let key in attributeMap) {
  (this.catalogForm.get('dynamicControls') as FormGroup).addControl(key, this.fb.control(attributeMap[key]))
  }
}

然后,在模板中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中,在.NET中。

<form [formGroup]="catalogForm">
 <section formGroupName="dynamicControls">
  <ng-container *ngFor=let control of catalogForm.get('dynamicControls').controls | keyvalue">
   <mat-form-field>
    <mat-label>{{control.key}}</mat-label>
    <input matInput type="text" [formControlName]="control.key"
   </mat-form-field>
 </ng-container>
</section>
</form>

在stackblitz上工作的例子

© www.soinside.com 2019 - 2024. All rights reserved.